LeetCode 91. 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).
给定一个数字字符串,找出其中可以转换成字母的各种数字的组合,最后输出转化方案数目。
递归回溯法:(超时)
class Solution {
public:
int numDecodings(string s) {
int max = s.size();
int ans = 0;
find(s,ans,0,0,max);
return ans;
}
void find(string s,int &ans,int cur,int len,int max){
if(cur+len>max){return;}
if(len!=0&&cur<max){
string tmp;
tmp.assign(s,cur,len);//就算len超出界限也会取得到
if(tmp[0] == '0') return;
int judge = atoi(tmp.c_str());//atoi的参数要求是char*
if(judge>=1&&judge<=26){
//cout<<cur<<" "<<judge<<endl;
cur+=len;
}else{
return;
}
}
find(s,ans,cur,1,max);
find(s,ans,cur,2,max);
if(cur==max){
ans++;
return;
}
}
};
其实这题应该用动态规划法求解的。但自己又想不明白。所以就去找到自己能理解的一种动态规划算法,先看一遍,读懂后再自己重构一边,之前的dfs也是这么学习的。
class Solution {
public:
int numDecodings(string s) {
int len = s.size();
vector<int> ans(len,0);
if(s[0]!='0'){
ans[0] = 1;
}else{
ans[0] = 0;
}
string tmp = s.substr(0,2);
int num = stoi(tmp);
if(num>=11&&num<=19 || num>=21&&num<=26) ans[1] = 2;
else if(num == 10 || num == 20) ans[1] = 1;
else if(num>=27 && tmp[1]!='0') ans[1] = 1;//30,40...都不行
for(int i=2;i<len;i++){
if(s[i]>='1'&&s[i]<='9'){
ans[i] += ans[i-1];
}
if(s[i-1]=='1'||s[i-1] == '2'&&s[i]<'7'){
ans[i] += ans[i-2];
}
}
return ans[len-1];
}
};
类似背包问题,从最底层开始向里面添加内容,添加到最高层时答案就出现了。