【第九周】646. Maximum Length of Pair Chain

原题

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]

leetcode地址:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

解题思路

这个题目属于LIS(最长上升子序列)的变种问题,将序列元素由单个数改为数对,然后求给出所有数对的最长上升子序列的长度。注意到关键点在于,数对的顺序是可以随意选择的;这是与LIS不同的另一点。

解决思路:先将数对进行从小到大排序,数对的大小规则:首先比较second位大小,如果相等则比较first位大小。排序后,就可以从小到大进行选择:由于序列中不能有重合部分,只需要设置一个Tag,记录当前序列最大数对的second值,在未遍历到的数对中,选择一个first值大于Tag的最小数对加入上升序列即可。所以我们只需要首先选择一个最小的数对加入上升序列,然后在排好序的数对中依次检索加入即可。这样获得到的序列一定是最长的。

算法复杂度:排序过程为O(nlogn),获取上升序列为O(n),故总复杂度为O(nlogn)。

发散问题:如果数对顺序不能改变,那么算法该如何选择?
思路:完全按照LIS算法实现即可,只需将数对看做单个数来进行比较即可。(也需要记录Tag防止重叠)

代码

class Solution {
public:
    int findLongestChain(vector<vector<int>>& pairs) {
        if (pairs.size() == 0) return 0;
        sort(pairs.begin(), pairs.end(), cmp);
        int count = 1, tag = pairs[0][1];
        for (int i = 1; i < pairs.size(); i++) {
            if (pairs[i][0] > tag) {
                tag = pairs[i][1];
                count++;
            }
        }
        return count;
    }
    static bool cmp(vector<int>& a, vector<int>& b) {
        if (a[1] < b[1] || a[1] == b[1] && a[0] < b[0]) return true;
        return false;
    }
};

总结

1、需要熟悉动态规划的各种基础问题及算法
2、灵活变通

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值