leetcode - 354 Russian Doll Envelopes

leetcode - 354 Russian Doll Envelopes

解题思路

原题链接

https://leetcode.com/problems/russian-doll-envelopes/description/

原题内容
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
动态规划
  • 为了方便,做如下处理
    • 将套娃的宽度从小到大排序,如果高度相同则宽度大的排在前面,这样是为了避免[5,4],[6,4]能被满足
      • 按高度从大到小排序envelopes.sort(key=lambda x:-x[1])
      • 再按宽度从小到大排序envelopes.sort(key=lambda x:x[0])
  • 动态方案
    • 这题类似于从数组中找出最长递增子数组,通过维护一个长子数组flag, 其中flag[i]表示长度为i的递增子数组中最后一个元素的最小的index

AC源码

Code (Python2)
class Solution(object):
    def maxEnvelopes(self, envelopes):
        if len(envelopes) == 0:
            return 0
        envelopes.sort(key=lambda x:-x[1])
        envelopes.sort(key=lambda x:x[0])
        dp = [0] * len(envelopes)
        dp[0] = 1
        maxDp = 1
        flag = [0]
        for i in range(1, len(envelopes)):
            j = len(flag) - 1
            if envelopes[flag[j]][1] < envelopes[i][1] and envelopes[flag[j]][0] < envelopes[i][0]:
                flag.append(i)
            else:
                while j >= 0:
                    if envelopes[flag[j]][1] < envelopes[i][1] and envelopes[flag[j]][0] < envelopes[i][0]:
                        break
                    j -= 1
                if envelopes[flag[j+1]][1] > envelopes[i][1]:
                    flag[j+1] = i
            dp[i] = dp[flag[j]] + 1 if j >= 0 else 1
            maxDp = max(maxDp, dp[i])
        return maxDp
Comment
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值