Leetcode 91. 解碼方法 Decode Ways

https://leetcode-cn.com/probl...python

遞歸解法

不用 functools.lru_cache 會超時code

import functools
class Solution:
    @functools.lru_cache()
    def numDecodings(self, s: str) -> int:
        if len(s) == 0 or s[0] == '0':
            return 0
        if len(s) == 1:
            return 1
        if len(s) == 2:
            x = 2 if (s[0] == '1' or s[0] == '2' and s[1] < '7') else 1
            if s[1] == '0': x -= 1
            return x
        x = self.numDecodings(s[1:])
        if s[0] == '1' or s[0] == '2' and s[1] < '7':
            x += self.numDecodings(s[2:])
        return x

若是 s 以 0 開頭則沒法解碼,返回 0
(若是 s 不以 0 開頭) s 長度爲 1 返回 1
長度爲 2,有四種狀況:既能夠做爲兩個一位數字(都不是 0),也能夠做爲兩位數字,例如 ‘12’。只能做爲兩個數字,如 ‘32’。只能做爲一個兩位數,只有兩種狀況 ‘10’ 、‘20’。沒法解析,如 ‘30’。遞歸

而後若是長度大於 2 則能夠嘗試把字符串分紅:
第一位和後面的
前兩位和後面的(須要前兩位構成的數字在 1 - 26 範圍內)leetcode

動態規劃

class Solution:
    def numDecodings(self, s: str) -> int:
        l = len(s)
        if l == 0 or s[0] == '0': return 0
        if l == 1: return 1
        dp = [0] * l
        dp[0] = 1
        dp[1] = 2 if s[0] == '1' or s[0] == '2' and s[1] < '7' else 1
        if s[1] == '0': dp[1] -= 1
        print(dp)
        for i in range(2, l):
            if s[i] != '0':
                dp[i] += dp[i-1]
            if s[i-1] == '1' or s[i-1] == '2' and s[i] < '7':
                dp[i] += dp[i-2]
        return dp[-1]

dp[i] 有兩種狀況:
前一個若是不是 0 就能夠累加前一個的值,
若是前一個加當前的值大於 0 且小於 27 能夠累加前一個的前一個的值。字符串

歡迎來個人博客: https://codeplot.top/
個人博客刷題分類:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/get

相關文章
相關標籤/搜索