leetcode-91-解码方法

---恢复内容开始---

 

 题目描述:

leetcode-91-解码方法

 方法一:回溯(超时)

class Solution:
    def numDecodings(self, s: str) -> int:
        res = 0
        def backtrack(s):
            nonlocal res
            if not s:
                res += 1
                return
            if int(s[:1]) > 0: 
                backtrack(s[1:]) 
            if len(s) > 1 and not s[:2].startswith('0') and 0 < int(s[:2]) <= 26: 
                backtrack(s[2:])
        backtrack(s)
        return res

方法二:动态规划

class Solution:
    def numDecodings(self, s: str) -> int: 
        if not s or s.startswith('0'): 
            return 0 
        pre_pre = pre = 1 
        for i in range(1, len(s)): 
            cur = 0 
            if s[i] != '0': 
                cur += pre 
            if s[i - 1] != '0' and int(s[i - 1:i + 1]) <= 26: 
                cur += pre_pre 
            pre_pre, pre = pre, cur 
        return pre

 

上一篇:决策树信息熵(entropy),基尼系数(gini)


下一篇:回溯:分割问题