Russian Doll Envelopes

俄罗斯套娃

题目

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.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Note:
Rotation is not allowed.

Example:

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

解析重点

1.依题我们可以把寻找过程分为两步,第一步先对长进行排序,这样可以进行初步的嵌套,注意,这里对于相同的长度要按宽度反序排列,以便下一步使用。
2.第二步寻找最深的套娃,也就是寻找最长的升子序列,具体依赖于arr自带的二分查找。

java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0
|| envelopes[0] == null || envelopes[0].length != 2)
return 0;
Arrays.sort(envelopes, new Comparator<int[]>() {//数组按照长度排序,不过,需要注意的是当长度相同时,按照宽度的反序排序
public int compare(int[] arr1, int[] arr2) {//这么做的原因是确保下一步寻找最长上升子序列的时候,不会出现[3,3],[3,4]的情况
if (arr1[0] == arr2[0])
return arr2[1] - arr1[1];
else
return arr1[0] - arr2[0];
}
});
int dp[] = new int[envelopes.length];
int len = 0;
for (int[] envelope : envelopes) {//遍历查找最长上升子序列
int index = Arrays.binarySearch(dp, 0, len, envelope[1]);//查看当前值在序列的位置,注意,这里用到arr自带的二分查找方法
if (index < 0) //当查找的数据不在数组里时,会返回一个index=-第一个大于该键的元
index = -(index + 1); //素的位置,当查找的数据超过数组时返回len+1,这样就可以找到最长递
dp[index] = envelope[1]; //增子序列
if (index == len)
len++;

}
return len;
}
}
undefined