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).
http://www.cnblogs.com/grandyang/p/4313384.html
方法1: DP
与climb stairs类似,考虑如果将当前一位和之前分割(此时要求当前数!= 0),和当前两位和之前分割(此时要求前一位是1|| 是2 && 当前位<= 6)。
dp(n + 1, 0): 当前字符为止,总decode ways。
initialization:dp[0] = 1, dp[1] = 1, all others 0,这里这一点很重要,因为这个dp存在累加dp[i] = dp[ i - 1], dp[i] += dp[i - 2],初始化必须是0。
tranfer: dp[i] = dp[ i - 1] (此时要求当前数!= 0), dp[i] += dp[i - 2] (此时要求前一位是1|| 是2 && 当前位<= 6)
return:dp.back()
易错点:
- 不要重复计算可能性
- 这是字符串,必须用s[i - 1] == “1” 来判断而不是s[i - 1] == 1
- dp[i] = dp[ i - 1], dp[i] += dp[i - 2]: 两项的结果是累加的, 这也是为什么不能初始化为1。举个栗子:230,在第三位上结果就是0.
- Fibonacci 初始值是f(0) = 1, f(1) = 1
code
class Solution {
public:
int numDecodings(string s) {
if (s.empty() || s[0] == '0' ) return 0;
int n = s.size();
vector<int> dp(n + 1, 0);
dp[0] = 1;
dp[1] = 1;
for (int i = 1; i < n +1; i++){
if (s[i - 1] != '0') {
dp[i] = dp[i - 1];
}
// 这个&&之后的括号很重要。。。
// 表面上循环从第一个字符开始(第i个dp项),但是只有i > 1时才判断是否要跳两个数以前,避免了overflow, 也不用处理dp[1] = 1的特殊情况
if (i > 1 && (s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] - '0' <=6)) {
dp[i] += dp[i - 2];
}
}
// printVector(dp);
return dp[n];
}