问题: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.
思路:解码这种尝试性的操作,递归尝试肯定会超时。肯定是动态规划方法。
状态量H[i]表示,前i个数字存在的解码方法数。
递推关系:
1、当出现0时,0必须和其左边的数结合,如果左边不是1或者2,那必定是错误的编码。
2、当出现大于26时,则必须拆开的解码。
3、当出现11~26时,则出现两种解码方法。
初始条件要符合逻辑。
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
if(n == 0 || s[0] == '0')
return 0;
if(n == 1)
return 1;
int H[n+1];
H[0] = 1;
H[1] = 1;
for(int i=2;i<=n;i++)
{
if (s[i-1] == '0')
{
if(s[i-2] < '3' && s[i-2] > '0')
H[i] = H[i-2];
else
return 0;
}
else if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6'))
H[i] = H[i-1] + H[i-2];
else
H[i] = H[i-1];
}
return H[n];
}
};