问题描述
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[i]=max(dp[i],dp[j]+1),if envelopes[i][0]>envelopes[j][0]&& envelopes[i][1]>envelopes[j][1]。时间复杂度是n2。由于已经排好序,可以使用二分查找进行优化。维护一个高度递增的序列,其表示有效信封的高度,计算当前信封是否可以被套进某一层,即。为了避免相同宽度的信封被重复计算,在排序时相同宽度按照高度递减排序,这样只要当前宽度的某个信封可以套在外部,那么同一宽度的之后的信封必然不会被计算。代码如下:
public int maxEnvelopes(int[][] envelopes) {
if(envelopes==null||envelopes.length==0)
return 0;
int n=envelopes.length;
Arrays.sort(envelopes,new Comparator<int[]>(){
public int compare(int[]a,int[]b){
if(a[0]!=b[0])
return a[0]-b[0];
else
return b[1]-a[1];}
});
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(list.size()==0||list.get(list.size()-1)<envelopes[i][1])
list.add(envelopes[i][1]);
int l=0;
int r=list.size()-1;
while(l<r){
int m=l+(r-l)/2;
if(list.get(m)<envelopes[i][1])
l=m+1;
else
r=m;
}
list.set(r,envelopes[i][1]);//相同宽度,取能够套在外面的高度较小的那个信封
}
return list.size();
}
参考链接:http://bookshadow.com/weblog/2016/06/07/leetcode-russian-doll-envelopes/