Give 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.
Find the maximum number of nested layers of envelopes.
Example
Example 1:
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]).
Example 2:
Input:[[4,5],[4,6],[6,7],[2,3],[1,1]]
Output:4
Explanation:
the maximum number of envelopes you can Russian doll is 4 ([1,1] => [2,3] => [4,5] / [4,6] => [6,7]).
思路:先sort based on w,剩下的跟 LIS一模一样。可以用dp,O(N^2) 也可以用 Binary search的方法,O(NlogN);
主要问题是想清楚,为什么先w升序,然后h降序。看下面的图;
如果是都是升序,那么2,4,5,7,1 最后生成的数组是
3
34
345
3457
1457
而5和7 是一个w,是不能同时进去的,所以,先进7,然后用5去update7,正确的应该是
3
34
347
345
145
剩下的代码跟Longest Increasing Sequence的代码一模一样。
class Solution {
private class Node {
public int w;
public int h;
public Node(int w, int h) {
this.w = w;
this.h = h;
}
}
public int maxEnvelopes(int[][] envelopes) {
if(envelopes == null || envelopes.length == 0 || envelopes[0].length == 0) {
return 0;
}
int m = envelopes.length;
int n = envelopes[0].length;
Node[] nodes = new Node[m];
for(int i = 0; i < m; i++) {
nodes[i] = new Node(envelopes[i][0], envelopes[i][1]);
}
//这里为什么w incrase, h decrease, [6,5] [6,6] [6,7]
//只有[6,7]能够进去,[6,5] [6,6] 是套不进去的;所以要求最大的h来首先判断;
Arrays.sort(nodes, (a, b) -> (a.w != b.w ? a.w - b.w : b.h - a.h));
int[] tails = new int[m];
tails[0] = nodes[0].h;
int index = 0;
for(int i = 0; i < m; i++) {
int curh = nodes[i].h;
if(curh < tails[0]) {
tails[0] = curh;
} else if(curh > tails[index]) {
tails[++index] = curh;
} else {
tails[binarySearch(tails, 0, index, curh)] = curh;
}
}
return index + 1;
}
// find 1st index which larger than target;
private int binarySearch(int[] tails, int start, int end, int target) {
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(tails[mid] <= target) {
start = mid;
} else {
// tails[mid] > target;
end = mid;
}
}
if(tails[start] >= target) {
return start;
}
return end;
}
}
以下是DP的代码 O(N^2) :After sort w之后,根本不需要判断w,h ,因为dp判断的时候一起判断了。
class Solution {
public class Node {
public int w;
public int h;
public Node(int w, int h) {
this.w = w;
this.h = h;
}
}
public int maxEnvelopes(int[][] envelopes) {
if(envelopes == null || envelopes.length == 0 || envelopes[0].length == 0) {
return 0;
}
int m = envelopes.length;
int n = envelopes[0].length;
Node[] nodes = new Node[m];
for(int i = 0; i < m; i++) {
nodes[i] = new Node(envelopes[i][0], envelopes[i][1]);
}
Arrays.sort(nodes,(a, b) -> (a.w - b.w));
int[] dp = new int[m];
Arrays.fill(dp, 1);
int globalmax = 1;
for(int i = 1; i < m; i++) {
for(int j = 0; j < i; j++) {
if(nodes[j].h < nodes[i].h && nodes[j].w < nodes[i].w) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
globalmax = Math.max(globalmax, dp[i]);
}
return globalmax;
}
}