leetcode-91-Decode Ways

龍仔發表於2019-02-16

描述

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]。