[LeetCode] Maximum Length of Pair Chain 链对的最大长度[DP解法]

版权声明:作者:Britesun 欢迎转载,与人分享是进步的源泉! https://blog.csdn.net/qq_34807908/article/details/82078326

题目

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn’t use up all the given pairs. You can select pairs in any order.

  • Example 1:
    Input: [[1,2], [2,3], [3,4]]
    Output: 2
    Explanation: The longest chain is [1,2] -> [3,4]

  • Note:
    The number of given pairs will be in the range [1, 1000].

分析题目

  • 本题给了我们一些链对,规定了如果后面链对的首元素大于前链对的末元素,那么这两个链对就可以链起来,问我们最大能链多少个.
  • 如果长度为k的链在某些pairs[i]处结束并且pairs[i] [1] < pairs[j] [0],我们可以将该链扩展为长度为k + 1的链。
  • 由于规定了链对的首元素一定小于尾元素,我们需要比较的是某个链表的首元素和另一个链表的尾元素之间的关系,如果整个链对数组是无序的,那么就很麻烦.因此按第二个坐标对pairs进行排序,让dp [i]为以pairs[i]结尾的最长链的长度。当i < j 且pairs [i] [1] < pairs [j] [0]时,我们可以扩展链,因此我们有候选答案dp [j] = max(dp [j],dp [i] + 1)。

代码

Complexity - Time: O(n2), Space: O(n)

class Solution {
    public int findLongestChain(int[][] pairs) {
        int m = pairs.length, res = 0;
        int[] dp = new int[m];
        Arrays.fill(dp,1);
        Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
        for(int i = 0; i < m; i++){
            for(int j = 0; j < i;j++)
            {
                if(pairs[j][1] < pairs[i][0])
                    dp[i] = Math.max(dp[i],dp[j] + 1);
            }
        }
        for(int i = 0; i < m; i++)
            res = Math.max(res,dp[i]);
        return res;    
    }

}

猜你喜欢

转载自blog.csdn.net/qq_34807908/article/details/82078326