problem:
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.
thinking:
(1)这道题很经典,很考察 DP、边界条件,我调试了一个小时才 AC
(2)这道题不是要一一列出解码出来的字符串,而是求解码的方法数。采用深搜的方法可以一一打印出来解码后的字符串,但是对于该题时间复杂度坑定会超时。
(3)采用DP,开一个n大小的数组记录DP的最优子结构的解。DP的难点在于寻找状态转移方程
if(s.at(i)=='0')
{
if(s.at(i-1)=='1'||s.at(i-1)=='2')
{
a[i]=a[i-2];
continue;
}
else
return 0;
}
if(s.at(i-1)=='1' ||(s.at(i-1)=='2'&&(s.at(i)>'0'&&s.at(i)<'7')) )
a[i]=a[i-2]+a[i-1];
else
a[i]=a[i-1];从左往右遍历字符串,对于第i个数字怎么解码,要看第i、i-1能否一起解码。
code:
class Solution {
public:
int numDecodings(string s) {
int n=s.size();
vector<int> a(n,0);
if(n==0)
return 0;
if(s.at(0)=='0')
return 0;
if(n==1)
return 1;
a[0]=1;
if(s.at(1)=='0')
{
if(s.at(0)=='1' || s.at(0)=='2')
a[1]=1;
else
a[1]=0;
}
else if(s.at(0)=='1' || (s.at(0)=='2'&&(s.at(1)>'0'&&s.at(1)<'7')))
a[1]=2;
else
a[1]=1;
if(n==2)
return a[1];
for(int i=2;i<n;i++)
{
if(s.at(i)=='0')
{
if(s.at(i-1)=='1'||s.at(i-1)=='2')
{
a[i]=a[i-2];
continue;
}
else
return 0;
}
if(s.at(i-1)=='1' ||(s.at(i-1)=='2'&&(s.at(i)>'0'&&s.at(i)<'7')) )
a[i]=a[i-2]+a[i-1];
else
a[i]=a[i-1];
}
return a[n-1];
}
};原文地址:http://blog.csdn.net/hustyangju/article/details/45056701