题目:
计算有多少种不同的编码方式.
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.
动态规划,用f[i]表示前i个元素编码的方式数。因为最后一个编码可能取最后两个数字,也可能只取最后一个数字,所以f[i]=f[i-1]+f[i-2]。注意要判断能不能只取最后一个数字或者取最后两位数字,能取才加上去。边界条件是f[0]和f[1]。
复杂度:O(n)。
代码:
class Solution {
public:
int numDecodings(string s) {
if(s.length()==0) return 0;
vector<int> f(s.length(),0);
int temp;
if(s[0]>'0') f[0]++;
if(s.length()==1) return f[0];
if(s[1]>'0') f[1]=f[0];
temp=(s[0]-'0')*10+(s[1]-'0');
if(temp<=26&&temp>=10) f[1]++;
for(int i=2;i<s.length();i++)
{
if(s[i]>'0') f[i]+=f[i-1];
temp=(s[i]-'0')+(s[i-1]-'0')*10;
if(temp>=10&&temp<=26) f[i]+=f[i-2];
}
return f[s.length()-1];
}
};