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])
- 按高度从大到小排序
- 将套娃的宽度从小到大排序,如果高度相同则宽度大的排在前面,这样是为了避免[5,4],[6,4]能被满足
- 动态方案
- 这题类似于从数组中找出最长递增子数组,通过维护一个长子数组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