354. 俄罗斯套娃信封问题

给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

说明:
不允许旋转信封。

示例:

输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3 
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。


dp
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[] arr1,int[] arr2){
                if(arr1[0]==arr2[0])return arr2[1]-arr1[1];//descend on height if width are same.
                else return arr1[0]-arr2[0];//Ascend on width
            }
        });
        //Since the width is increasing, we only need to consider height.
        //then it's the same solution as [300.Find the longest increasing subsequence] based on height.
        int res=1;
        int[] dp=new int[envelopes.length];
        Arrays.fill(dp, 1);
        for(int i=0;i<envelopes.length;i++){
            for(int j=0;j<i;j++){
                if(envelopes[i][1]>envelopes[j][1]){
                    dp[i]=Math.max(dp[i],dp[j]+1);
                    res=Math.max(res,dp[i]);
                }
            }
        }
        return res;
    }
}

dp+binary search

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[] arr1,int[] arr2){
                if(arr1[0]==arr2[0])return arr2[1]-arr1[1];//descend on height if width are same.
                else return arr1[0]-arr2[0];//Ascend on width
            }
        });
        //Since the width is increasing, we only need to consider height.
        //then it's the same solution as [300.Find the longest increasing subsequence] based on height.
        int res=0;
        int[] dp=new int[envelopes.length];
        for(int[] e:envelopes){
            int index=Arrays.binarySearch(dp,0,res,e[1]);
            if(index<0)index=-(index+1);
            dp[index]=e[1];
            if(index==res)res++;
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xxxsans/p/14479184.html