[leetcode]646. Maximum Length of Pair Chain
Analysis
突然期待 hhh—— [每天刷题并不难。。。]
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.
动态规划解决~
Implement
class Solution {
public:
static bool cmp(const vector<int> &v1, const vector<int> &v2){
if(v1[1] == v2[1])
return v1[0] <= v2[0];
else
return v1[1] < v2[1];
}
int findLongestChain(vector<vector<int>>& pairs) {
int len = pairs.size();
sort(pairs.begin(), pairs.end(), cmp);
int dp[len];
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for(int i=1; i<len; i++){
for(int j=i-1; j>=0; j--){
if(pairs[i][0] > pairs[j][1]){
dp[i] = dp[j] + 1;
break;
}
}
dp[i] = max(dp[i-1], dp[i]);
}
return dp[len-1];
}
};