LN : leetcode 646 Maximum Length of Pair Chain
lc 646 Maximum Length of Pair Chain
646 Maximum Length of Pair Chain
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.
Example 1:
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
Note:
The number of given pairs will be in the range [1, 1000].
DP Accepted
dp[i]表示前i+1个可以组成链的数对个数,先将数对根据第一个数进行从小到大的排序,可以得出动态转移方程为dp[i] = max(dp[i], pairs[i][0] > pairs[j][1]? dp[j] + 1 : dp[j])
。
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), cmp);
vector<int> dp(pairs.size(), 1);
for (int i = 0; i < pairs.size(); i++) {
for (int j = 0; j < i; j++) {
dp[i] = max(dp[i], pairs[i][0] > pairs[j][1]? dp[j] + 1 : dp[j]);
}
}
return dp[pairs.size()-1];
}
static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
};
普遍方法 Accepted
根据每一对的第二个值将所有数对进行从小到大的排序,此时,循环遍历整个数组如果前一成链数对的第二个数小于当前遍历数对的第一个数,则又可以成链。这个方法很直观且简单。
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), cmp);
int maxlen = 1;
for (int i = 0, j = 1; j < pairs.size(); j++) {
if (pairs[i][1] < pairs[j][0]) {
maxlen++;
i = j;
}
}
return maxlen;
}
static bool cmp(vector<int>& a, vector<int>& b) {
return a[1] < b[1];
}
};