码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-91-解码方法

时间:2019-07-13 15:04:11      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:col   turn   alt   coding   info   超时   image   com   src   

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

 

 题目描述:

技术图片

 方法一:回溯(超时)

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

 

leetcode-91-解码方法

标签:col   turn   alt   coding   info   超时   image   com   src   

原文地址:https://www.cnblogs.com/oldby/p/11180599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!