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;
}