LeetCode No.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.

===================================================================

題目鏈接:https://leetcode.com/problems/decode-ways/

題目大意:求一共有多少種解碼方式,其中解碼規則是:‘A'對應1,‘B’對應2,……,‘Z’對應26

思路:動態規劃,新建一個長度爲n+1的數組dp,其中dp[0]=1,dp[i]表示s前面i個字符的解碼方式。

1、當是s[i]=='0'時,如果前面一個數字不存在或者不是1、2,則直接返回0,否則dp[i+1]=dp[i-1]。

2、i>0且當s[i-1]=='1'時或者s[i-1]==2且s[i]>='1',s[i]<='6'時,dp[i+1] = dp[i] + dp[i-1]。

3、其他情況下,dp[i+1] = dp[i] 。

參考代碼:

class Solution {
public:
    int numDecodings(string s) {
        int n = s.size() ;
        if ( n == 0 )
            return 0 ;
        vector <int> dp ( n + 1 , 0 ) ;
        dp[0] = 1 ;
        for ( int i = 0 ; i < n ; i ++ )
        {
            if ( s[i] == '0' )
            {
                if ( i == 0 || ! ( s[i-1] >= '1' && s[i-1] <= '2' ) )
                    return 0 ;
                dp[i+1] = dp[i-1] ;
            }
            else if ( i && ( s[i-1] == '1' || ( s[i] >= '1' && s[i] <= '6' && s[i-1] == '2' ) ) )
                dp[i+1] = dp[i] + dp[i-1] ;
            else
                dp[i+1] = dp[i] ;
            
        }
        return dp[n] ;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章