力扣-354.俄罗斯套娃信封问题

本文介绍了一种解决信封问题的方法,通过宽度升序排列并结合最长递增子序列算法,找出在宽度相等时高度最高的信封组合。关键步骤包括使用lambda表达式对信封按特定规则排序,并利用动态规划求解最长递增子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,将宽度升序,如果宽度一样则对高度降序(因为要先找到同宽中最大的信封装)

然后,再将排序后的高度,求最长递增子序列力扣-300.最长递增子序列_Node_Su的博客-优快云博客

例如原先数据:     经过以上步骤后:

[5,4]                       [2,3]

[6,4]                       [5,4]

[6,7]                       [6,7]

[2,3]                       [6,4]

最终求得高度的最长递增子序列:[2,3]=>[5,4]=>[6,7]

其中有一个方便的办法执行“首先”的步骤

envelopes.sort(key=lambda x: (x[0], -x[1]))

key=lambda是固定的,x[0]表示排序,x[1]表示键值排序,默认是升序

class Solution(object):
    def maxEnvelopes(self, envelopes):
        """
        :type envelopes: List[List[int]]
        :rtype: int
        """
        envelopes.sort(key=lambda x: (x[0], -x[1]))
        height = []
        for i in range(0, len(envelopes)):
            height.append(envelopes[i][1])
        res = self.lengthOfLIS(height)
        return res

    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [1] * (len(nums))

        for i in range(0, len(nums)):
            for j in range(0, i):  # 此处不需要查找所有比当前的nums[i]小的nums[j],只需查找在nums[i]之前的小的nums[j]即可
                if nums[j] < nums[i]:
                    dp[i] = max(dp[i], dp[j] + 1)  # 与当前更长的dp[j]+1
        res = 0
        for i in range(0, len(dp)):
            res = max(res, dp[i])
        return res


if __name__ == '__main__':
    envelopes = [[5, 4], [6, 4], [6, 7], [2, 3]]
    Sol = Solution()
    res = Solution.maxEnvelopes(Sol, envelopes)
    print(res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值