leetcode-91-Decode Ways

描述

A message containing letters from A-Z is being encoded to numbers

using the following mapping:

‘A’ -> 1 ‘B’ -> 2 … ‘Z’ -> 26 Given an encoded message containing
digits, determine the total number of ways to decode it.

For example,

Given encoded message “12”, it could be decoded as “AB” (1 2) or “L”

(12).

The number of ways decoding “12” is 2.


class Solution:
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        if s[0]=='0' :
            return 0
        elif len(s)==1:
            return 1

        length=len(s)
        dp=[0 for _ in range(length+1)]
        print('dp:==>',dp)
        dp[0]=1
        dp[1]=1
        for i in range(2,length+1):
            l2=int(s[i-2:i])
            l1=int(s[i-1:i])
            if 10<l2<27  and s[i-1]!='0':
                dp[i]=dp[i-1]+dp[i-2]
            elif l2==10 or l2==20:
                dp[i]=dp[i-2]
            elif s[i-1]!='0':
                dp[i]=dp[i-1]
            else:
                return 0
        # print(dp[length-1]+dp[length-2])
        # print('dp=-=>',dp)
        out=dp[length]
        return out
if __name__=='__main__':
    st=Solution()
    num='2626'
    num='0'
    num='11'
    num='1'
    num='0'
    num='11'
    num='110'
    out=st.numDecodings(num)
    print(out)

解释:本地是动态规划解决,所以需要分清楚往后叠加增加字符时的数目之间的变化规律。经总结,发现当前字符前面的两个字符和一个字符可以拿出来进行分析。 当前的数目可以作为cur_index-2和cur_index-1的数目的叠加。只跟前两个位置的字符处产生的数目有关系。
所以dp关系式是:dp[n]=dp[n-1]+dp[n-2].其他的特殊情况可以进行特殊处理。比如10,20,位数为1的情况。 需要注意的是:如果钱两位是10,20,则这两位作废,不能计入其他情况的统计,即 dp[i]=dp[i-2]。

    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000013749911
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞