题目
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.
思路
递归解法
class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s.length()<1)
return 0;
int sum = 0;
myNumDecode(s,0,sum);
return sum;
}
void myNumDecode(string &S, int cur, int &sum){
if(cur==S.length())
{
sum = sum+1;
return ;
}
if(S[cur]=='0')
return ;
myNumDecode(S,cur+1,sum);
if(cur+1<S.length()) {
char a = S[cur];
char b = S[cur+1];
if((a-'0')*10+b-'0'<=26)
myNumDecode(S,cur+2,sum);
}
}
};
DP 动态规划解法
class Solution {
public:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = s.length();
if(len==0)
return 0;
vector<int> num(len+1,0);
num[0] = s[0]=='0'?0:1;
for(int i=1;i<=len;i++) {
if(s[i-1]!='0')
num[i] += num[i-1];
if(i>=2 && (s[i-2]=='1' || s[i-2]=='2' && s[i-1] <='6'))
num[i] += num[i-2];
}
return num[len] ;
}
};
991

被折叠的 条评论
为什么被折叠?



