Leetcode 645.最长数对链

最长数对链

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

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

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

示例 :

输入: [[1,2], [2,3], [3,4]]

输出: 2

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

注意:

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

思路

Intuition

If a chain of length k ends at some pairs[i], and pairs[i][1] < pairs[j][0], we can extend this chain to a chain of length k+1.

Algorithm

Sort the pairs by first coordinate, and let dp[i] be the length of the longest chain ending at pairs[i]. When i < j and pairs[i][1] < pairs[j][0], we can extend the chain, and so we have the candidate answer dp[j] = max(dp[j], dp[i] + 1).

 1 import java.util.Arrays;
 2 
 3 class Solution {
 4     public int findLongestChain(int[][] pairs) {
 5         Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
 6         int N = pairs.length;
 7         int[] dp = new int[N];
 8         Arrays.fill(dp, 1);
 9 
10         for (int j = 1; j < N; ++j) {
11             for (int i = 0; i < j; ++i) {
12                 if (pairs[i][1] < pairs[j][0])
13                     dp[j] = Math.max(dp[j], dp[i] + 1);
14             }
15         }
16 
17         int ans = 0;
18         for (int x: dp) if (x > ans) ans = x;
19         return ans;
20     }
21 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10383060.html