您的位置:首页 > 大数据 > 人工智能

[Leetcode] 646. Maximum Length of Pair Chain 解题报告

2018-01-24 12:40 429 查看
题目

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].

4000


1、动态规划:

首先对pairs进行正常排序,然后定义dp[i]表示以第i个pair为结尾的最长pair chain的长度,那么递推公式为:dp[i] = max(dp[j] + 1), j < i并且dp[j][1] < dp[i][0]。计算出每个dp值之后,返回dp数组中的最大值即可。算法的空间复杂度是O(n),时间复杂度是O(n^2)。

2、贪心法:

如果我们采用另外一种排序方法,也就是按照pairs的第二个数进行升序排序,那么还可以用更简单的贪心算法:我们依次遍历,如果当前的pair能够连接到上一个pair,就连接,否则就跳过。这是因为最终的pair chain一定是目前这种排序后的序列的一个子序列(可以用反证法证明),所以对于每个节点而言,我们要么不连接它,要么连接它。如果能连接,我们就连接。为什么呢?这是因为如果不连接该点,那么pairs数组中的下一个节点的end point比当前一定更靠后(因为这就是排序依据),所以导致能连接到的最终pair个数不会比选择连接当前节点更长。贪心算法本身的时间复杂度是O(n),但是由于贪心之前还需要排序,所以整体算法的时间复杂度是O(nlogn)。空间复杂度可以做到O(1)。

代码

1、动态规划:

class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end());
vector<int> dp(pairs.size(), 1);
for (int i = 1; i < dp.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (pairs[j][1] < pairs[i][0]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
return *(max_element(dp.begin(), dp.end()));
}
};
2、贪心法:

class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), cmp);
int cnt = 0;
vector<int>& pair = pairs[0];
for (int i = 0; i < pairs.size(); i++) {
if (i == 0 || pairs[i][0] > pair[1]) {  // pairs[i][0] can be behind pair
pair = pairs[i];
cnt++;
}
}
return cnt;
}
private:
static bool cmp(vector<int>& a, vector<int>&b) {
return a[1] < b[1] || a[1] == b[1] && a[0] < b[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: