题目:
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.
思路:
思路1,利用NP的想法递归,但是时间复杂度太大。 思路2,为了简化时间复杂度,我们采用动态规划的方法。例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件: 1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。 2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
代码:
思路1:
class Solution {
public:
int count;
int numDecodings(string s) {
if(s.size()==0)
{
return 0;
}
count=0;
Decode(s,0,0);
return count;
}
void Decode(string s, int begin, int end)
{
if(begin>=s.size())
{
count++;
}
else if(end>=s.size())
{
return;
}
else
{
int num=0;
for(int i =begin;i<=end;i++)
{
num*=10;
num+=s[i]-'0';
}
if(num>=1&&num<=26)
{
Decode(s,end+1,end+1);
}
if(num>=1&&num<=2)
{
Decode(s,begin,end+1);
}
}
}
};
思路2
class Solution {
public:
int numDecodings(string s) {
if(s.size() == 0){
return 0;
}
else if(s.size() == 1){
return s[0] != '0' ? 1 : 0;
}
else if(s.size() == 2){
return (s[0] != '0' && s[1] != '0'? 1 : 0) + ((s[0] != '0' && (char2int(s[0]) * 10 + char2int(s[1])) <= 26) ? 1 : 0);
}
int* dp = new int[s.size()];
dp[0] = s[0] != '0' ? 1 : 0;
dp[1] = (s[0] != '0' && s[1] != '0'? 1 : 0) + ((s[0] != '0' && (char2int(s[0]) * 10 + char2int(s[1])) <= 26) ? 1 : 0);
for(int i = 2; i < s.size(); i++){
dp[i] = 0;
if(s[i] != '0'){
dp[i] += dp[i-1];
}
if(s[i-1] != '0' && (char2int(s[i-1]) * 10 + char2int(s[i])) <= 26){
dp[i] += dp[i-2];
}
}
return dp[s.size() - 1];
}
int char2int(char c){
return c - '0';
}
};