Question:
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.
Solution:
- solution1:
class Solution {
public:
int numDecodings(string s) {
int len = s.size();
if(len < 1 || s[0] == '0'){
return 0;
}
if(len == 1){
return 1;
}
int m[len][len];
for (int i = 0 ; i < len ;i++){
m[i][i] = s[i] == '0'?1:0;
}
int max = 0;
for(int l = 1 ; l < len ; l++){
for(int i = 0; i < len-l; i++){
int j = i + l ;
if(s[i] == '0'){
m[i][j] = 0;
continue;
}
for(int k = i ; k < j ; k++){
string str = s.substr(i,2);
if(str == "00"){
return 0;
}
int tmp = m[i][k] > m[k+1][j] ? m[i][k]:m[k+1][j];
if(str <= "26" && str >= "11"){
tmp += 1;
}
if(tmp > max){
max = tmp;
}
}
}
}
return max;
}
};
思路是:s[i][j] = max{s[i][k]+s[k+1][j]} +1 , “10” < s[k][k+1] < “27”
max{s[i][k]+s[k+1][j]},否则
结果超时.
- solution2:
递归关系式应该为:m[i] = m[i-1]+m[i-2], 当s[i-1] == 0
时m[i-1] = 0
class Solution {//解题思路参照某位大神
public:
int numDecodings(string s) {
if(s.empty() || s[0] == '0'){
return 0;
}
int len = s.size();
int res = 1;
int pre = 1;
for(int i = 2 ; i <= len; i++){
int f = (s[i-1] == '0' ? 0 : res);
string str = s.substr(i-2,2);
if(str >= "10" && str <= "26"){
f += pre;
}
pre = res;
res = f;
}
return res;
}
};