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].
算法分析
问题大意为对于一组成对的数,每对数中第一个数小于第二个数。定义由一个成对的数构成的序列,相邻元素间前面一对数的第二个值小于后面一对数的第一个值。找到由给定一组成对的数构成的数组形成的序列的最大长度。序列中不需要包含给定数组的所有元素。
算法分析:
1、先将数组中元素按照元素中的第二个值作为关键字进行排序。
2、使用动态规划解决问题。定义数组dp[],dp[i]表示序列终止在第i个元素时序列的最大长度。
3、dp[i]可由dp[j]得到(j元素的第二个值小于i元素的第一个值),即第i元素可以链接在由j结束的数组中。如果dp[j]+1 > dp[i], dp[i] = dp[j] + 1。得到以第i元素结束的序列的最大长度。
4、问题的结果为dp数组的最大值。
代码实现
@requires_authorization
bool less_second(const vector<int>& a, const vector<int>& b) {
if (a[1] < b[1])
return true;
return false;
}
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), less_second);
int *dp = new int[pairs.size() + 1];
for (int i = 0; i < pairs.size(); i++) {
dp[i] = 1;
}
for (int i = 1; i < pairs.size(); i++) {
for (int j = 0; j < i; j++) {
if (pairs[j][1] < pairs[i][0]&&dp[i] < dp[j] + 1)
dp[i] = dp[j] + 1;
}
}
int MAX = 0;
for (int i = 0; i < pairs.size(); i++) {
if (dp[i] > MAX)
MAX = dp[i];
}
return MAX;
}
};