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

相关文章
相关标签/搜索