第十六周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]; }};
- leetcode-第十六周
- 第十六周leetcode
- 第十六周LeetCode
- 第十六周LeetCode
- 第十六周LeetCode
- LeetCode题解 第十六周
- leetcode 第十六周解题报告
- 第十六周LeetCode算法题两道
- 第十六周:[leetCode] 79. Word Search
- leetcode【第十六周】左叶子节点求和
- leetcode第十六周解题总结--图
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- 第十六周
- linux开机启动mongodb
- spring框架之快速入门
- 程序员面试宝典随笔记(一)-----C++智能指针初步
- Atom 使用基本命令
- LeetCode之Find Smallest Letter Greater Than Target(Kotlin)
- 第十六周LeetCode
- 商品列表,未支付,已支付
- go的web编程
- IO设计模式:Reactor和Proactor对比
- Q-1-HTML-1
- mysql常用操作
- hdu 1372 Knight Moves(骑士遍历/跳马问题)
- mongo安全:增加用户名密码
- 又一种Qt + OpenGL 的离屏渲染方法