第十六周LeetCode

来源:互联网 发布:origin 画图 mac 编辑:程序博客网 时间:2024/05/23 12:44

题目
Maximum Length of Pair Chain
难度 Medium

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

实现思路

这道题是最长递增子序列的一个变体。对于 pair (c, d) 和pair (a, b),若b < c则假设pair (a, b)存在一条边指向pair (c, d)。因此先将pairs从小到大排序(以检查b和c的大小关系),然后用dp[i]记录以pairs[i]为终点的最长递增子序列长度,则dp[i]的长度取决于指向pairs[i]的dp[j]的长度,取与dp[i]相连的最长的dp[j]+1,表示以i为终点的最长递增子序列长度。

实现代码

class Solution {public:    //从小到大排序    static bool comp(const vector<int> &first, const vector<int> &second ) {        if (first[0]==second[0]) {            return first[1]<second[1];        }        return first[0]<second[0];    }    int findLongestChain(vector<vector<int>>& pairs) {        sort(pairs.begin(),pairs.end(),comp);        vector<int> dp(pairs.size(),1);        for (int i = 0; i < pairs.size(); i++) {            for (int j = 0; j < i; j++) {                dp[i] = max(dp[i],(pairs[i][0] > pairs[j][1]?dp[j]+1:dp[j]));            }        }        return dp[pairs.size()-1];    }};
原创粉丝点击