646. Maximum Length of Pair Chain

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了646. Maximum Length of Pair Chain相关的知识,希望对你有一定的参考价值。

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:

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

题目含义:给定一组数对,我们定义当且仅当b < c时,(c, d)可以链在(a, b)之后。求可以组成的最长数对链的长度。

 

 1     public int findLongestChain(int[][] pairs) {
 2 //        p[i]储存的是从i结束的链表长度最大值。首先初始化每个dp[i]为1。然后对于每个dp[i],找在 i 前面的索引 0~j,
 3 //        如果存在可以链接在i 前面的数组,且加完后大于dp[i]之前的值,那么则在dp[j]的基础上+1.
 4         Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
 5         int i, j, max = 0, n = pairs.length;
 6         int dp[] = new int[n];
 7         Arrays.fill(dp,1);
 8         for (i = 1; i < n; i++)
 9             for (j = 0; j < i; j++)
10                 if (pairs[j][1] < pairs[i][0] && dp[i] < dp[j] + 1)
11                     dp[i] = dp[j] + 1;
12 
13         for (i = 0; i < n; i++) if (max < dp[i]) max = dp[i];
14         return max;        
15     }

 

以上是关于646. Maximum Length of Pair Chain的主要内容,如果未能解决你的问题,请参考以下文章

646. Maximum Length of Pair Chain

646. Maximum Length of Pair Chain

646. Maximum Length of Pair Chain

646. Maximum Length of Pair Chain

[leetcode-646-Maximum Length of Pair Chain]

646. Maximum Length of Pair Chain 对链最大长度