[LeetCode] Number of decoding 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.

思路:用动态规划。

    int numDecodings(string s)
    {
        if(s.length()==0) return 0;
        
        vector<int> table(s.length()+1, 0);
        if(s.at(0)=='0')
            return 0;
        else
        {
            table[0]=1; // this line is important for input such as "10"
            table[1]=1;
        }
        
        if(s.length()>1)
            for(int i=1; i<s.length(); i++)
                numDecodingsUtil(s.substr(0,i+1), table);
            
        return table[s.length()];
    }

    void numDecodingsUtil(string s, vector<int>& table) 
    {
        // table stores the intermediate results
        // After calling this function, table[s.length()] will be set to the number of decodings for string s
        int len = s.length();
        int sum = s.at(len-1) - '0';
        
        int num = 0; 
        if(sum!=0)
            num = table[len-1];
            
        sum = sum+10*( s.at(len-2)-'0' );
        if(sum>=10 && sum<=26)
            num = num+table[len-2];
        
        table[len] = num;
    }



你可能感兴趣的:(LeetCode)