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.
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.
题意:字母A-Z对应1-26,则给出一串数字有多少种解法。
思路:dfs + dp
class Solution {
public:
int numDecodings(string s) {
vector<int> dp(s.size(), -1);
return dfs(s, dp);
}
int dfs(string s, vector<int>& dp){
if (s.empty())
return 0;
if (s[0] == '0'){
dp[s.size() - 1] = 0;
return 0;
}
if (dp[s.size() - 1] != -1){
return dp[s.size() - 1];
}
else{
int m = s.size();
if (m == 1){
dp[m - 1] = 1;
}
else if(m == 2){
if (s[1] == '0'){
if (s[0] == '1' || s[0] == '2'){
dp[m - 1] = 1;
}
else{
dp[m - 1] = 0;
}
}
else{
if (s[0] == '2' && s[1] > '6')
dp[m - 1] = 1;
else if (s[0] > '2'){
dp[m - 1] = 1;
}
else{
dp[m - 1] = 2;
}
}
}
else{
if (s[0] =='1' || (s[0]=='2' && s[1]<='6'))
dp[m - 1] = dfs(s.substr(1, m - 1), dp) + dfs(s.substr(2, m - 2), dp);
else{
dp[m - 1] = dfs(s.substr(1, m - 1), dp);
}
}
return dp[m - 1];
}
}
};