[LeetCode] Maximum Length of Pair Chain 链对的最大长度[DP解法]

给定一对数字,若后一个对的第一个数字大于前一个对的第二个数字,则可以形成链对。从给定的一组对中找出能形成的最长链对。例如,输入[[1,2], [2,3], [3,4]],输出2,最长链对为[1,2] -> [3,4]。解题策略包括对pairs按第二个元素排序,然后使用动态规划求解,时间复杂度为O(n^2),空间复杂度为O(n)。" 84181901,7345414,Ubuntu系统下配置IPv4+DHCP和IPv6+radvd路由器,"['网络配置', 'Ubuntu系统', 'IPv4设置', 'IPv6设置', 'DHCP服务器']
摘要由CSDN通过智能技术生成

题目

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

分析题目

  • 本题给了我们一些链对,规定了如果后面链对的首元素大于前链对的末元素,那么这两个链对就可以链起来,问我们最大能链多少个.
  • 如果长度为k的链在某些pairs[i]处结束并且pairs[i] [1] < pairs[j] [0],我们可以将该链扩展为长度为k + 1的链。
  • 由于规定了链对的首元素一定小于尾元素,我们需要比较的是某个链表的首元素和另一个链表的尾元素之间的关系,如果整个链对数组是无序的,那么就很麻烦.因此按第二个坐标对pairs进行排序,让dp [i]为以pairs[i]结尾的最长链的长度。
    当i < j 且pairs [i] [1] < pairs [j] [0]时,我们可以扩展链,因此我们有候选答案dp [j] = max(dp [j],dp [i] + 1)。
    #代码
    Complexity - Time: O(n2), Space: O(n)
class 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值