646. Maximum Length of Pair Chain

来源:互联网 发布:上海数据录入公司 编辑:程序博客网 时间:2024/06/05 09:00

题目

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: 2Explanation: The longest chain is [1,2] -> [3,4]

Note:

  1. The number of given pairs will be in the range [1, 1000].

分析

一种方法是动态规划,利用自带的sort函数对pairs进行排序,然后用dp从头开始记录下来当前项所处的最长连接的长度,但是这需要O(n^2)的复杂度和O(n)的空间,自带的sort排序对pairs的处理是按照pair对的第一个元素大小排序,如果第一个元素相等,则按照第二个的大小排序,对于最长的连接,我们希望前面的pair第二个元素尽可能小,这样后面才能连接到更多的pair,因此可以自定义sort排序的比较函数,对于第二个元素相同的,令第一个元素小的在前面,否则令第二个元素小的在前面,这样只需要对候选集进行一次遍历,将其拆分为连接好的和待连接的,同时能够计算出来长度。

动态规划如下:

class Solution {public:    int findLongestChain(vector<vector<int>>& pairs) {        sort(pairs.begin(),pairs.end());//先对候选集进行排序(可以处理此情况)        int dp[1001];//利用动态规划记录第i处的最长链长        for(int i=0;i<pairs.size();++i){//遍历候选集            dp[i]=1;//初始化为1            for(int j=0;j<i;++j){//从前i项中找到某个符合条件的最长链长加上当前pair作为第i项的最长链长                if(pairs[j][1]<pairs[i][0]){                    dp[i]=max(dp[i],dp[j]+1);                }            }        }        return dp[pairs.size()-1];    }};
O(logn)的算法如下:

bool cmp(vector<int> &a, vector<int> &b){    return a[1] == b[1] ? a[0] < b[0]: a[1] < b[1];}class Solution {public:    int findLongestChain(vector<vector<int>>& pairs) {        sort(pairs.begin(),pairs.end(),cmp);//先对候选集进行排序(可以处理此情况)        int last = pairs[0][1];//以第1项的第2个元素作为筛选依据        int res = 1;        for(int i = 1; i < pairs.size();++i){//在后续中寻找,找到符合条件的,更新链长的末尾元素,并增加长度            if(pairs[i][0] > last){                ++res;                last = pairs[i][1];            }        }        return res;    }};



原创粉丝点击