地址:https://leetcode.com/problems/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 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。
感觉这种思路其实有些混乱。
class Solution {
public:
int numDecodings(string s) {
return ways(s, 0);
}
private:
int ways(const string& str, int begin) {
if (begin >= str.length()) return 1;
if (str[begin] >= '3')
return ways(str, begin + 1);
else if (str[begin] == '2') {
if (begin == str.length() - 1)
return ways(str, begin + 1);
else {
if (str[begin + 1] >= '7')
return ways(str, begin + 1);
else
return ways(str, begin + 1) + ways(str, begin + 2);
}
}
else if (str[begin] == '1') {
if (begin == str.length() - 1)
return ways(str, begin + 1);
else
return ways(str, begin + 1) + ways(str, begin + 2);
}
else
return 0;
}
};
实现2:
这种实现使用了dp,dp就是迭代版的化简。
从头开始判断,dp
的第i位存的是s的子串s[0...i-1]
的可能解码方式总数。
class Solution {
public:
int numDecodings(string s) {
if (s[0] == '0') return 0;
else if (s.size() == 1) return 1;
vector<int> dp(s.size() + 1, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i < dp.size(); ++i) {
if (s[i - 1] > '0') dp[i] = dp[i - 1];
if (s[i - 2] == '1' || (s[i - 2] == '2'&&s[i - 1] <= '6')) dp[i] += dp[i - 2];
}
return dp.back();
}
};