LeetCode-【动态规划】-最长数对链

版权声明:转载注明出处就可以了。。。 https://blog.csdn.net/zw159357/article/details/82562884

给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。

现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面。我们用这种形式来构造一个数对链。

给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。

示例 :

输入: [[1,2], [2,3], [3,4]]
输出: 2
解释: 最长的数对链是 [1,2] -> [3,4]

注意:

  1. 给出数对的个数在 [1, 1000] 范围内。

题解:先按数对中的第二个数字从大到小排序,已知数对中的第一个数字总是比第二个数字小,这样排序后,根据贪心策略,每次尽量选取第二个数字较小的数对,这样留给后面的选择空间就会变大,也就是能组成的连续对数链更长,根据这个思路很容易写出代码,动规的与这个大同小异,只不过动规记录每个阶段的比较结果而已。

贪心解法:

class Solution {
    public int findLongestChain(int[][] pairs) {
        int m=pairs.length;
        int n=pairs[0].length;
        Arrays.sort(pairs,new Comparator<int[]>(){
           public int compare(int[] a,int[] b){
               return a[1]-b[1];
           } 
        });
        int res=0;
        int end=Integer.MIN_VALUE;
        for(int i=0;i<m;i++){
            if(pairs[i][0]>end){
                res++;
                end=pairs[i][1];
            }
        }
        return res;
    }
}

动规解法:

class Solution {
    public int findLongestChain(int[][] pairs) {
        if(pairs == null || pairs.length == 0)
            return 0;
        int rows = pairs.length;
        int cols = pairs[0].length;
        Arrays.sort(pairs, new Comparator<int[]>(){
            public int compare(int[] a,int[] b){
                 return a[0] - b[0];
            }
         });       
        int[] dp = new int[rows];
        dp[0] = 1;
        for(int i=1;i<rows;i++){
            for(int j=0;j<i;j++){
                if(pairs[i][0] > pairs[j][1])
                    dp[i] = Math.max(dp[i],dp[j]+1);
                else
                    dp[i] = Math.max(dp[i],dp[j]);
            }
        }
        return dp[rows-1];
    }
}

猜你喜欢

转载自blog.csdn.net/zw159357/article/details/82562884