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.
Example
Given encoded message 12
, it could be decoded as AB
(1 2) or L
(12).
The number of ways decoding 12
is 2.
思路是通过DFS来解决, 注意一些边界条件。
但是这样仍然引入的大量重复计算,所以过程中将已经计算过的string存起来, 节省时间, 类似dp的思想:
class Solution {
public:
/**
* @param s a string, encoded message
* @return an integer, the number of ways decoding
*/
int numDecodings(string& s) {
// Write your code here
unordered_map<string, int> map;
int res = numDecodings_helper(s, map);
return res;
}
int numDecodings_helper(string& s, unordered_map<string, int>& map) {
if (s[0] == '0') {
return 0;
}
if (s.size() <= 1) {
return s.size();
}
if (map.find(s) != map.end()) {
return map[s];
}
int res1 = 0;
int res2 = 0;
if (s[1] != '0') {
string s1 = s.substr(1, s.size() - 1);
res1 = numDecodings_helper(s1,map);
}
string t = s.substr(0,2);
if (t <= "26") {
if (s.size() >= 3) {
string s2 = s.substr(2, s.size() - 2);
res2 = numDecodings_helper(s2, map);
} else {
res2 = 1;
}
}
map[s] = res1 + res2;
return res1 + res2;
}
};