LeetCode 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].
分析
这道题利用动态规划思想就是判断某个pair的所在链的末端位置就要寻找它最靠近它的前面一个pair的位置,然后+1。整道题的思路就是先将所有的pair以前一个为主键进行排序,然后对每一个pair都记录它的右值,即到这个点的最大值,另外往前找,找到刚好可以作为这个pair的前一个pair以确定该pair在该链的位置。待确定所有pair的链位置之后,找出pair在链中的最大位置就是所有链中的最大长度。
关键代码
while(j >= 0) {
if (pairs[i][0] > max[j] && dp[i] <= dp[j]) {
dp[i] = dp[j]+1;
break;
}
j--;
}
复杂度分析:时间复杂度为O(n2),空间复杂度为O(n)
代码
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
int _size = pairs.size();
for (int i = _size-1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (pairs[j][0] > pairs[j+1][0]) {
int temp = pairs[j+1][0];
pairs[j+1][0] = pairs[j][0];
pairs[j][0] = temp;
temp = pairs[j+1][1];
pairs[j+1][1] = pairs[j][1];
pairs[j][1] = temp;
}
}
}
int* dp = new int[_size];
int* max = new int[_size];
for (int i = 0; i < _size; i++) {
dp[i] = 1;
max[i] = pairs[i][1];
if (i == 0) continue;
int j = i-1;
while(j >= 0) {
if (pairs[i][0] > max[j] && dp[i] <= dp[j]) {
dp[i] = dp[j]+1;
break;
}
j--;
}
}
int maxLen = 1;
for (int i = 0; i < _size; i++) {
if (dp[i] > maxLen) maxLen = dp[i];
}
return maxLen;
}
};
附
题目地址:LeetCode646