# [91] 解码方法
#动态规划
#dp【i】表示从0-i个数字表示的映射数
# @lc code=start
class Solution:
def numDecodings(self, s: str) -> int:
lens=len(s)
dp=[0 for _ in range(lens)]
if s[0]!="0":
dp[0]=1
else:
return 0
if len(s)==1:
return dp[0]
else:
x=1 if s[1]!="0" and dp[0]!=0 else 0
y=1 if int(s[0:2]) in range(10,27) else 0
dp[1]=x+y
for i in range(2,lens):
x=dp[i-1] if s[i]!="0" and dp[i-1]!=0 else 0
y=dp[i-2] if int(s[i-1:i+1]) in range(10,27) else 0
dp[i]=x+y
return dp[lens-1]
# @lc code=end
# @lc app=leetcode.cn id=90 lang=python3
#
# [90] 子集 II
#
# @lc code=start
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
def combine(n: int, k: int):
rev=list()
res=list()
import copy
def f(n,k):
if k==0:
re=copy.deepcopy(rev)
res.append(re)
return
else:
for i in range(n,k-1,-1):
rev.append(nums[i-1])
f(i-1,k-1)
rev.pop()
f(n,k)
return res
re=list()
nums.sort()
for i in range(len(nums)+1):
res=combine(len(nums),i)
for item in res:
if not item in re:
re.append(item)
return re
# @lc code=end
# @lc app=leetcode.cn id=89 lang=python3
#
# [89] 格雷编码
#
# @lc code=start
class Solution:
def grayCode(self, n: int) -> List[int]:
def subgrayCode(n):
mid=list()
if n==1:
return ["0","1"]
else:
res=subgrayCode(n-1)
lens=len(res)
for i in range(lens):
mid.append("0"+res[i])
for i in range(lens-1,-1,-1):
mid.append("1"+res[i])
return mid
x=subgrayCode(n)
for i in range(len(x)):
x[i]=int(x[i],2)
return x
# @lc code=end
# @lc code=start
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
# maxs=0
# for i in range(len(heights)):
# for j in range(i,len(heights)):
# ms=min(heights[i:j+1])
# maxs=max(maxs,ms*(j-i+1))
# return maxs
n = len(heights)
left, right = [0] * n, [0] * n
mono_stack = list()
for i in range(n):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
left[i] = mono_stack[-1] if mono_stack else -1
mono_stack.append(i)
mono_stack = list()
for i in range(n - 1, -1, -1):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
right[i] = mono_stack[-1] if mono_stack else n
mono_stack.append(i)
ans = max((right[i] - left[i] - 1) * heights[i] for i in range(n)) if n > 0 else 0
return ans