91. Decode Ways
# Medium
class Solution:
def numDecodings(self, s: str) -> int:
dp = [0 for i in range(len(s)+1)]
dp[0] = 1
for i in range(len(s)):
if s[i] == '0':
dp[i+1] = 0
else:
dp[i+1] = dp[i]
# the condition must be like this
# eg, '10001', '01', '27', '30'
if i >= 1 and ((s[i-1] == '1') or (s[i-1] == '2' and s[i] <= '6')):
dp[i+1] += dp[i-1]
return dp[-1]
必须要跟上面的代码写得一模一样,不然就会出错,DP能够处理更大的数据。由于dp[i]
最多只取决于dp[i-1]
和 dp[i-2]
,时间复杂度为 ,由于只使用了dp这个 数组,所以空间复杂度为
Last updated
Was this helpful?