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]).
给出二维数组,分别代表信封的宽和长(width, height)。像俄罗斯套娃一样把一个信封装入另一个信封,问最多能装多少层信封。
装入另一个信封的条件是长和宽都比另一个小。
思路:
降维,然后转化为dp
宽按升序排序,长按降序排序:
把宽按升序,保证每一个宽都能装进下一个信封,这样就不用考虑宽,只需要考虑长。
然后长按降序排列,将问题转化为300.Longest Increasing Subsequence
有两种方法解决longest increasing subsequence
目的是找到最长的升序子序列,也就是能装入下一个信封的数量
具体参考上面300题的链接:
(1) O(n2)
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0) {
return 0;
}
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] arr1, int[] arr2) {
if (arr1[0] == arr2[0]) {
return (arr2[1] - arr1[1]);
} else {
return (arr1[0] - arr2[0]);
}
}
});
int[] dp = new int[envelopes.length];
Arrays.fill(dp, 1);
int maxLen = 1;
for (int i = 1; i < envelopes.length; i++) {
for (int j = 0; j < i; j++) {
//每次从头开始找比它小的元素
if (envelopes[i][1] > envelopes[j][1]) {
dp[i] = Math.max(dp[j] + 1, dp[i]);
if (dp[i] > maxLen) {
maxLen = dp[i];
}
}
}
}
return maxLen;
}
(2) O(nlogn) binary Search
//9ms
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0) {
return 0;
}
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] arr1, int[] arr2) {
if (arr1[0] == arr2[0]) {
return (arr2[1] - arr1[1]);
} else {
return (arr1[0] - arr2[0]);
}
}
});
int[] dp = new int[envelopes.length];
Arrays.fill(dp, 1);
int len = 0;
for(int[] envelope : envelopes){
//直接从之前的元素中找到比它小的
int index = Arrays.binarySearch(dp, 0, len, envelope[1]);
if(index < 0) {
//index = 0;
//这里这样写的原因,是因为binarySearch返回的结果一次找不到会是-1,然后会-2,-3,为了把index转换到对应的元素位置,这样处理
index = -(index + 1);
}
dp[index] = envelope[1]; //保存现有元素
//len = Math.max(len, index+1);
if(index == len)
len++;
}
return len;
}