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].
解题思路:
数对含有第一位(前者)和第二位(后者),先根据后者大小来排序,这样就已经制约了一个界限,作为前后数对比较的界限。
这样第一个取数对,从第一界限取,由于没有前面的数对可比较,同一个后者,前者取谁都可以,
第二个数对从排序的第二个界限取,则需要判断其前者是否大于前一个数对后者,若可以就取这个数,
依次进行循环结束即可。
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), cmp);
int n = pairs.size();
int count=0;
for(int i=0, j=0; j<n; j++){
if(j==0 || pairs[i][1]<pairs[j][0]){
count++;
i = j;
}
}
return count;
}
static bool cmp(vector<int> &a,vector<int> &b){
return a[1]<b[1];
}
};
使用动态规划:
首先好好排序,完整的按照先前者后后者的排序方法。
在这个序列中,到第i个形成的最长链问题可能包含前面的一些子链。
问题缩小,到达第i个时判断前面pairs[i][0]是否大于pairs[j][1],若大于,那么第i个可以加到前一个上(假设前一个长度为n),这里i的最长度为n+1,判断是否大于之前的最大值,若大于则更行dp[i];
若pairs[i][0]小于pairs[j][1],那么是不能加在前一个i-1上的,dp[i]值不变;
这样从0-i循环一遍后第i的最长链就确定了。
再回到大循环i从0到n-1遍历一遍,最后dp[n-1]就是最后的结果。
class Solution {
public:
int findLongestChain(vector<vector<int>>& pairs) {
sort(pairs.begin(), pairs.end(), cmp);
int n = pairs.size();
vector<int> dp(n,1);
for(int i=0; i<n; i++){
for(int j=0; j<i; j++){
dp[i] = max(dp[i], pairs[i][0] > pairs[j][1] ? dp[j] + 1: dp[i]);
}
}
return dp[n-1];
}
static bool cmp(vector<int> &a,vector<int> &b){
if(a[0]!=b[0]){
return a[0]<b[0];
}else{
return a[1]<b[1];
}
}
};