首先,将宽度升序,如果宽度一样则对高度降序(因为要先找到同宽中最大的信封装)
然后,再将排序后的高度,求最长递增子序列力扣-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)