LeetCode 646 : Maximum Length of Pair Chain(c++)

原题

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

思路

本题有点动态规划和贪心的意思。大意是找出能够组成符合题目要求的最长的链长度。题目已知在任何数对(a, b) 中,a < b;且数对(a, b)和 (c, d)能组成链当且仅当b < c。
已知数对是无序出现的,所以首先第一步要对数对进行排序,排序的原则是先对第二个元素进行升序排序,在此基础上对第一个元素进行升序排序。
假设有以下一组数对:
[[-6,9],[1,6],[8,10],[-1,4],[-6,-2],[-9,8],[-5,3],[0,3]]
经过排序后变成:
[[-6,-2],[-5,3],[0,3],[-1,4],[1,6],[-9,8],[-6,9],[8,10]]
用dp[i]表示排完序后前i个数对能够组成的最长的链子,则必有dp[i+1]>=dp[i];另外dp[i]与距离其最近的能组成链的dp[j](j<i)的关系为dp[i]=dp[j]+1,所谓能组成链,必有dp[i][0]>dp[j][1]

代码

class Solution {
public:
    static bool cmp(const vector<int> &v1,const vector<int> &v2){
        if(v1[1]==v2[1])
            return v1[0]<=v2[0];
        else
            return v1[1]<v2[1];
    }
    int findLongestChain(vector<vector<int>>& pairs) {
        int nPairs=pairs.size();
        sort(pairs.begin(),pairs.end(),cmp);
        int dp[nPairs];
        memset(dp,0,sizeof(dp));
        dp[0]=1;
        for(int i=1;i<nPairs;i++){
            for(int j=i-1;j>=0;j--){
                //往前查找,只要能够接在pairs[i]之前的pairs[j],dp[i]=dp[j]+1
                //因为pairs[i][1]在升序排序的基础上,pairs[i][0]也按升序排序,所以仅需找到离pairs[i]最近的pairs[j]即可执行break
                if(pairs[j][1]<pairs[i][0]){
                    dp[i]=dp[j]+1;
                    break;
                }
            }
            //由于pairs[i][1]是按升序排序的,所以必有dp[i]>=dp[i-1]
            dp[i]=max(dp[i-1],dp[i]);
        }
        return dp[nPairs-1];
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值