Simple DP.
Scanning from the end. If current is 0, then no decode way as "0", but it can be treated as "10", "20". So do another check whether it can have other combinations from i+2.
But if the last one is "0", there is no way to decode it except len-2 is "1" or "2". So assign one more space to dp for holding 1 way for the special case.
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 int len = s.size(); 5 if (len == 0) return 0; 6 vector<int> dp(len+1, 1); 7 for (int i = len-1; i >= 0; i--) { 8 if (s[i] == '0') dp[i] = 0; 9 else dp[i] = dp[i+1]; 10 11 if (i < len-1 && (s[i] == '1' || (s[i] == '2' && s[i+1] <= '6'))) dp[i] += dp[i+2]; 12 } 13 return dp[0]; 14 } 15 };