• 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;
        }
    }
  • 相关阅读:
    再见了亲爱的学生们,再见了敬爱的同事们,再见了信狮
    #if defined 和#ifdef的区别
    C# ASP.NET Core开发学生信息管理系统(二)
    modelsim与debussy联合的问题
    C#批量生成大数据量无重复随机数据的另类高效实现
    DataColumn.Caption属性应用到DataGridView.HeaderText的方法
    [转载]安装网银安全控件
    近期学习SQL Server,收藏的几个学习教程网址备忘
    asp.net根据域名查ip C#版
    asp.net 2.0教程 成员资格和角色管理
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14479184.html
Copyright © 2020-2023  润新知