Leetcode354. Russian Doll Envelopes

给定一个二维整数数组envelopes,表示信封的宽高。问题要求找到可以完全放入另一信封的最大信封数量,不考虑旋转。通过将问题转化为一维长增序问题并利用bisect_left优化求解,得出最大嵌套信封数。

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

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

这个问题相当于Longest Increasing Subsequence的二维版本

思路就是固定一个维度,对另外一个维度求Longest Increasing Subsequence

使用dp来做会有个别case超时

LIS中如果新找的数比所有a中的数都大,append到a中。否则把a中对应的index位置更新为num

逻辑是做更新的这一步,更新为了更小的值,使得后续能加入的更多了。

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        a = []
        for num in nums:
            idx = bisect.bisect_left(a, num)
            if idx == len(a):
                a.append(num)
            else:
                a[idx] = num
        return len(a)

    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        envelopes.sort(key = lambda x: (x[0], -x[1]))
        #reduce to 1D
        height = [y for _,y in envelopes]
        return self.lengthOfLIS(height)

        

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值