力扣OJ 646. 最长数对链

时光毁灭记忆、已成空白 提交于 2020-01-20 01:33:22

题目:

给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。

现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面。我们用这种形式来构造一个数对链。

给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。

示例 :

输入: [[1,2], [2,3], [3,4]]
输出: 2
解释: 最长的数对链是 [1,2] -> [3,4]
注意:

给出数对的个数在 [1, 1000] 范围内。

 

分析:

动态规划。

因为数据量只有1000,所以直接写个简单的O(n*n)的时间的算法即可

代码:

bool cmp(vector<int> it1,vector<int> it2)
{
    return it1[1]<it2[1];
}

class Solution {
public:
    int findLongestChain(vector<vector<int>>& pairs) {    
        int res=0;
        vector<vector<int>>ans;
        vector<int>temp;
        ans.clear();        
        sort(pairs.begin(),pairs.end(),cmp);
        for(auto it=pairs.begin();it!=pairs.end();it++){
            temp.clear();
            temp.insert(temp.end(),(*it)[1]);
            temp.insert(temp.end(),1);
            for(auto it2=ans.begin();it2!=ans.end();it2++){
                if((*it)[0]>(*it2)[0] && temp[1]<(*it2)[1]+1){
                    temp[1]=(*it2)[1]+1;
                }
            }
            ans.insert(ans.end(),temp);
            if(res<temp[1]){
                res=temp[1];
            }
        }
        return res;
    }
};

还有一种贪心的算法:

以第二个数为第一关键字,第一个数为第二个关键字,进行排序。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!