March-354. Russian doll envelope issue

 

class Solution:
    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        # dp = [1]*len(envelopes)
        # if not envelopes:
        #     return 0
        #超出时间限制
        # envelopes = sorted(envelopes,key = lambda x:x[0])
        # print(envelopes)
        # res = 1
        # #动态转移方程;以dp[i]结尾组成的最长严格递增子序列的长度
        # for i in range(1,len(envelopes)):
        #     for j in range(i):
        #         if envelopes[i][0]>envelopes[j][0] and envelopes[i][1]>envelopes[j][1]:
        #             dp[i] = max(dp[i],dp[j]+1)
            
        #     res = max(res,dp[i])
        
        # return res


        if not envelopes:
            return 0
        N = len(envelopes)
        #对第一个维度进行升序,第二个维度进行降序,只考虑第二维度即可
        #因为按照第一个维度进行升序排序的时候,如果遇到第一维相同的值,那么第二维度可以进行降序,这样保证了后一个能套住前一个
        envelopes.sort(key=lambda x: (x[0], -x[1]))
        res = 0
        dp = [1] * N
        for i in range(N):
            for j in range(i):
                if envelopes[j][1] < envelopes[i][1]:
                    dp[i] = max(dp[i], dp[j] + 1)
        return max(dp)
  • Dynamic programming
    • Both the first dimension and the second dimension are in ascending order
      • The dynamic transfer equation is dp[i]=max(dp[j]+1,dp[i])
      • Compare both the first dimension and the second dimension
    • The first dimension is in ascending order, the second dimension is in descending order
      • The equation of state remains the same as above
      • Compare only the second dimension

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/114373059