354. Russian Doll Envelopes
题目描述
有许多给定长宽(w, h)的信封。当且仅当当前信封的长宽都大于另一个的时,才可以把另一个信封放入当前信封中。(不允许翻转信封)
问:你可以套的最大信封数?
例子
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)
时间复杂度O(n^2)。
dp[i]表示以envelopes[i]结尾的最长递增子序列。
(法2 - 改进)
dp[i]表示长为i+1的最小元素(长度相同情况下有一个最小的h)。若大于dp[-1],直接append;否则,找到第一个大于该元素的,替换。
(w,h)首先按w升序,我们把w当成索引(肯定有序)。
然后按h降序,设计算法使得h升序。(若h刚开始升序排列,则类似[5,3],[6,4],[6,7],[6,4]直接被丢弃了。)
解法1 - TLE
常规DP,时间复杂度O(n^2)。
dp[i]表示以envelopes[i]结尾的最长递增子序列。
class Solution(object):
def maxEnvelopes(self, envelopes):
"""
:type envelopes: List[List[int]]
:rtype: int
"""
if not envelopes:
return 0
n = len(envelopes)
envelopes.sort(key = lambda x:(x[0], x[1]))
dp = [1] * n
for i in range(1, n):
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)
return max(dp)
解法2
改进,二维的LIS,时间复杂度O(nlogn)。
class Solution(object):
def maxEnvelopes(self, envelopes):
"""
:type envelopes: List[List[int]]
:rtype: int
"""
if not envelopes:
return 0
n = len(envelopes)
envelopes.sort(key = lambda x:(x[0], -x[1]))
dp = [envelopes[0][1]]
for _, h in envelopes[1:]:
if h > dp[-1]:
dp.append(h)
else:
pos = self.helper(dp, h)
dp[pos] = h
return len(dp)
def helper(self, arr, target):
l, r = 0, len(arr)-1
while l <= r:
mid = (l + r) >> 1
if arr[mid] < target:
l = mid + 1
else:
if mid > 0 and arr[mid-1] >= target:
r = mid - 1
else:
return mid
338. Counting Bits
题目描述
给定一个非负整数num。对0 ≤ i ≤ num区间内的每个数字i,计算二进制表示中的1的数目。
例子
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
思想
(法1 - 利用内置函数)
(法2 - DP)
如何统计1的数目?
假设n为100…,则n-1为00…1,n&(n-1)=0。说明n&(n-1)消去了末尾的1
(法3 - DP)
dp[i]表示 i的二进制中1的数目。
首先记录i的最后一位是否为1;然后i的二进制表示右移一位,变成⌊i/2⌋ 的二进制。
解法1
利用内置函数
class Solution(object):
def countBits(self, num):
return [bin(i).count('1') for i in range(num+1)]
解法2
(DP)
假设n为100…,则n-1为00…1,n&(n-1)=0。说明n&(n-1)消去了末尾的1
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0]
for i in range(1, num+1):
res.append(res[i & (i-1)] + 1)
return res
解法3
dp[i]表示 i的二进制中1的数目。dp[i] = dp[i/2] + (i&1)
首先记录i的最后一位是否为1;然后i的二进制表示右移一位,变成⌊i/2⌋ 的二进制。
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0]
for i in range(1, num+1):
dp.append(dp[i>>1] + (i&1))
return dp