A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226" Output: 3 Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
解题思路:动态规划,有点类似走楼梯,一次走一个或者两个,问有多少种走法。不同的是本题限制了什么时候可以跨两步,什么时候能跨一步。两种情况。
每增加一位:
①若该位不为‘0’(对应走楼梯,就是可以走一步),则dp[i] = dp[i] + dp[i-1]
②若该位与前一位组成的数字在10 - 26(对应走楼梯,就是可以走两步),则dp[i] = dp[i] + dp[i-2]
class Solution {
public:
int numDecodings(string s) {
int len = s.length();
if(len == 0)
return 0;
vector<int>num(len + 2, 0);
num[0] = 1;
num[1] = s[0] == '0' ? 0 : 1;
for(int i = 2; i <= len; ++ i){
int temp = 10 * (s[i - 2] - '0') + s[i - 1] - '0';
if(s[i - 2] != '0' && temp <= 26 && temp >= 1)
num[i] = num[i - 2];
if(s[i - 1] != '0')
num[i] += num[i - 1];
}
return num[len];
}
};