Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
法一:动态规划
和LeetCode第300题(最长子序列)思路一样。
public int findLongestChain(int[][] pairs) {
//按照区间end进行升序排列
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
int n = pairs.length;
int[] dp = new int[n];//dp[i] 表示以pairs[i]结尾的最长链的长度
for(int i = 0; i < n; i ++) {
int max = 1;
for(int j = 0; j < i; j ++) {
if(pairs[i][0] > pairs[j][1]) {
max = Math.max(max, dp[j] + 1);
}
}
dp[i] = max;
}
int res = 0;
for(int i = 0; i < n; i ++) {
res = Math.max(res, dp[i]);
}
return res;
}
法二:贪心
public int findLongestChain(int[][] pairs) {
//按照区间end进行升序排列
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
int res = 1;
int end = pairs[0][1];
for(int i = 1; i < pairs.length; i ++) {
if(pairs[i][0] > end) {
res ++;
end = pairs[i][1];
}
}
return res;
}