解码方法
- 91 Decode Ways
- 考点:递推 或者 动态规划
class Solution {
public:
int numDecodings(string s) {
// 进阶版 青蛙跳台阶
// f[i]表示前i个数总的解码方案数,分析最后一个不同点,第i位可以是一个字符组成的字母,也可以和前一位结合组成的字母。
int n = s.size();
s = ' ' + s;
vector<int> f(n+1);
f[0] = 1; //空串只能解码出一种空串的方案 ‘A’==>'1' 同理 ''==>''
for(int i = 1; i <= n; i++){
if(s[i] >= '1' && s[i] <= '9') f[i] += f[i-1];
if(i > 1){
int t = (s[i-1]-'0')*10 + s[i] - '0';
if(t >= 10 && t <= 26) f[i] += f[i-2];
}
// cout<<f[i]<<endl;
}
return f[n];
}
};
解码方法2
考点:动态规划 + 递归 + 字母性质
- 枚举1到26进行匹配
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
s = ' ' + s;
vector<long long> f(n+1);
const int MOD = 1e9+7;
f[0] = 1; // 一个数字都没有为空 空也是一种方案
for(int i = 1; i <= n; i++){
for(int j = 1; j <= 26; j++){
char a = s[i];
if(j <= 9){
if(a == j + '0' || a =='*') f[i] += f[i-1];
}else if(i >= 2){
int b = s[i-1];
int y = j/10, x = j%10;
// ba == yx 十位和个位同时进行匹配
if((b == y +'0' || b == '*' && y) && (a == x +'0' || a=='*' && x))
f[i] += f[i-2];
}
f[i] %= MOD;
}
}
return f[n];
}
};