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.

Solution: dp. Note that '0' must be decoded in together with the number in front of it.

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         if (s.empty() || s[0] == '0') 
 5             return 0;
 6         int N = s.size();
 7         int dp[N+1];
 8         dp[0] = 1;
 9         dp[1] = 1;
10         for (int i = 1; i < N; ++i)
11         {
12             if (s[i] == '0')
13             {
14                 if (s[i-1] != '1' && s[i-1] != '2')
15                     return 0;
16                 dp[i+1] = dp[i-1];
17             }
18             else
19             {
20                 int num = s[i] - '0' + (s[i-1] - '0') * 10;
21                 if (num >= 11 && num <= 26)
22                     dp[i+1] = dp[i] + dp[i-1];
23                 else
24                     dp[i+1] = dp[i];
25             }
26         }
27         return dp[N];
28     }
29 };
原文地址:https://www.cnblogs.com/zhengjiankang/p/3682148.html