面试题43:计算多少种译码方式(decode-ways)
这道题是非常典型的DP问题。按照DP的套路,关键是讨论出递推表达式,遍历过程中针对当前字符是否为'0'以及前一个字符为'0',分类讨论得出到目前字符为止最多有多少种译码方式?理清了递推表达式,代码是很简单的。
A message containing letters fromA-Zis 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
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 int n = s.length(); 5 vector<int> dp(n + 1, 0); 6 7 if (n == 0 || s[0] == '0') return 0; 8 9 dp[0] = 1; 10 dp[1] = 1; 11 for (int i = 2; i <= n; i++) { 12 if (s[i-1] == '0' && s[i - 2] == '0') 13 return 0; 14 else if (s[i-2] == '0') { 15 dp[i] = dp[i - 1]; 16 }else if(s[i-1] == '0'){ 17 if(s[i-2] > '2') return 0; 18 dp[i] = dp[i-2]; 19 }else { 20 dp[i] = dp[i - 1]; 21 if (stoi(s.substr(i - 2, 2)) <= 26) { 22 dp[i] += dp[i - 2]; 23 } 24 } 25 26 } 27 return dp[n]; 28 } 29 };