來自 https://leetcode.com/problems/russian-doll-envelopes/ide
You have a number of envelopes with widths and heights given as a pair of integers (w, h)
. One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.code
What is the maximum number of envelopes can you Russian doll? (put one inside other)排序
Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]]
, the maximum number of envelopes you can Russian doll is 3
([2,3] => [5,4] => [6,7]).ip
這個題目是最長子序列的變形;最長子序列能夠參考https://en.wikipedia.org/wiki/Longest_increasing_subsequenceleetcode
本題目的解法:it
1. 先將長方形按照寬排序,若是寬度同樣, 按照高度降序排列,即 wi < wj or wi == wj && hi > hj; 這樣獲得的序列,從寬度考慮,前面的確定能夠放入後面的;對於wi == wj && hi > hj是由於在寬度一致的狀況下,將更高的放在前面,能夠保證後面根據高度查找最長子序列的時候,將這種組合排除;class
2. 而後根據高度查找能夠嵌套的最長子序列便可;im
func maxEnvelopes(envelopes [][]int) int { sort.Sort(byShape(envelopes)) m := make([]int, len(envelopes)+1, len(envelopes)+1) L := 0 for i, a := range envelopes { lo, hi := 1, L for lo <= hi { mid := (lo + hi) / 2 b := envelopes[m[mid]] if b[1] < a[1] { lo = mid + 1 } else { hi = mid - 1 } } m[lo] = i if L < lo { L = lo } } return L } type byShape [][]int func (a byShape) Len() int { return len(a) } func (a byShape) Less(i, j int) bool { if a[i][0] != a[j][0] { return a[i][0] < a[j][0] } return a[j][1] < a[i][1] } func (a byShape) Swap(i, j int) { a[i], a[j] = a[j], a[i] }