https://leetcode.com/problems/maximum-length-of-pair-chain/description/
Solution 1.
int findLongestChain(vector<vector<int>>& pairs) {
if(pairs.size() == 0) return 0;
sort(pairs.begin(), pairs.end(), [&](vector<int>&a, vector<int>&b){
if(a[1]==b[1]) return a[0] < b[0];
return a[1] < b[1];
});
int res = 1;
int preVal = pairs[0][1];
for(int i=1; i<pairs.size(); i++) {
if(pairs[i][1] > preVal && pairs[i][0] > preVal) {
res++;
preVal = pairs[i][1];
}
}
return res;
}
Solution 2. Recursion
int help(vector<vector<int>>& pairs, int preVal, int cur, int len) {
if(cur == pairs.size()) {
return len;
}
int i=cur;
while(i<pairs.size() && pairs[i][1] == pairs[cur][1]) i++;
i--;
if(cur == 0)
return help(pairs, pairs[i][1], i+1, 1);
else if(pairs[i][0] > preVal)
return help(pairs, pairs[i][1], i+1, len+1);
else
return help(pairs, preVal, i+1, len);
}
int findLongestChain(vector<vector<int>>& pairs) {
if(pairs.size() == 0) return 0;
sort(pairs.begin(), pairs.end(), [&](vector<int>&a, vector<int>&b){
if(a[1]==b[1]) return a[0] < b[0];
return a[1] < b[1];
});
return help(pairs, 0, 0, 0);
}
No comments:
Post a Comment