354. Russian Doll Envelopes

xiaoxiao2021-02-27  336

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)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]).

思路:最开始想到的是排序+DP求LIS类似的思路,复杂度O(N^2),

import java.util.Arrays; import java.util.Comparator; public class Solution { public int maxEnvelopes(int[][] envelopes) { if(envelopes == null || envelopes.length == 0) return 0; Arrays.sort(envelopes, new Comparator<int[]>(){ public int compare(int[] o1, int[] o2) { if(o1[0] == o2[0]) return o1[1]-o2[1]; return o1[0]-o2[0]; } }); // dp[i] means best result from envelopes[0] to envelopes[i](necessary included) int[] dp = new int[envelopes.length]; int[] curMax = new int[dp.length]; Arrays.fill(dp, 1); Arrays.fill(curMax, 1); int max = 1; for(int i=1; i<dp.length; i++) { for(int j=i-1; j>=0; j--) if(envelopes[j][0]<envelopes[i][0] && envelopes[j][1]<envelopes[i][1]) { dp[i] = Math.max(dp[i], dp[j]+1); if(dp[i] == curMax[i]) break; } max = Math.max(max, dp[i]); curMax[i] = Math.max(curMax[i-1], dp[i]); } return max; } }

后来发现求LIS可以有N*logN的解法,如下:

那这个题能不能用呢?如果按照上面的排序策略是不行的,因为你不能确定(2,5),(3,4)谁比较小,这取决于后面的数据,

换种思路:已经按照width排好了序,那我们只需要考虑height,求height的LIS,但是相同的width的只能有一个啊,那相同的width就按照height降序排,这样一旦选取了某个height,后面相同width的height就不可能选了,前面的也不可以,in this way,NlogN is achieved

import java.util.Arrays; import java.util.Comparator; /* * 1. Sort: Ascend on width, descent on height * 2. find the longest increasing subsequence based on height * * in this way, the same width can only have one and we can run LIS using binary search. * since with same width, latter coming will always has smaller height, hi will always decrease until * cross over the reigon of same width */ public class Solution { public int maxEnvelopes(int[][] envelopes) { if(envelopes == null || envelopes.length == 0) return 0; Arrays.sort(envelopes, new Comparator<int[]>(){ public int compare(int[] o1, int[] o2) { if(o1[0] == o2[0]) return o2[1]-o1[1]; return o1[0]-o2[0]; } }); // LIS, since the height, we can do it in NlogN int[] h = new int[envelopes.length]; int len = 0; for(int[] a : envelopes) { int insert = Arrays.binarySearch(h, 0, len, a[1]); if(insert < 0) insert = -(insert+1); // if not find h[insert] = a[1]; if(insert == len) len++; } return len; } }

转载请注明原文地址: https://www.6miu.com/read-3056.html

最新回复(0)