题目描述
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)
样例
Input: [[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]).
算法1
(土味DP)
01背包般的DP 可惜最后一个case python 超时
$O(n^2)$
PYTHON3 代码
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if envelopes == []:
return 0
envelopes.sort()
e = envelopes
dp = [1 for i in range(len(envelopes))]
for i in range(1,len(dp)):
dp[i] = max(dp[j] + 1 if (e[i][0] > e[j][0] and e[i][1] > e[j][1]) else dp[i] for j in range(0,i))
return max(dp)
算法2
(LIS 参考 LEETCODE 300)
用长作为高度的位置准则,例如[[5,4],[6,4],[6,7],[2,3]] 根据长度排序得到[[2,3],[5,4],[6,7],[6,4]] (如果长度相同则按照高度逆序排列,这点很关键) 然后提取出序列[3,4,7,4] 找longest Incressing Subsequence长度
$O(nlgn)$
https://www.acwing.com/solution/LeetCode/content/9613/
Python3 代码
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
e = envelopes
if e == []:
return 0
e.sort(key = lambda x: (x[0],-x[1]))
h = [c[1] for c in e]
res = []
for i in h:
left = bisect.bisect_left(res,i)
if left == len(res):
res.append(i)
else:
res[left] = i
return len(res)