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.
int DFS(string &s, int step, int len)
{
if (step == len)
{
return 1;
}
int count = 0;
if (s[step] != '0')
{
// 解析一个,只有下一个不为0才可以
if (!(step + 1 < len && s[step + 1] == '0'))
{
count += DFS(s, step + 1, len);
}
// 解析两个,只有s[step] <= 2
if (step + 1 < len && s[step - 1] > '0')
{
string tmp = s.substr(step - 1, 2);
if (atoi(tmp.c_str()) <= 26)
count += DFS(s, step + 2, len);
}
}
return count;
}
int numDecodings(string s)
{
if (s == "")
return 0;
int len = s.length();
return DFS(s, 0, len);
}
DP:OK
int numDecodings2(string s)
{
if (s == "")
return 0;
int size = s.length();
int ans = 0;
int *f = new int[size + 2];
f[0] = 1;
f[1] = 1;
for (int i = 0; i < size; ++i)
{
f[i+2] = 0;
if (s[i] == '0')
{
if (i == 0 || s[i-1] == '0' || s[i-1] > '2')
{
return 0;
}
else
{
f[i+2] += f[i];
}
}
else
{
// 一个
f[i+2] += f[i+1];
// 两个
if (i > 0 && s[i-1] > '0')
{
string tmp = s.substr(i-1, 2);
if (atoi(tmp.c_str()) <= 26)
{
f[i+2] += f[i];
}
}
}
}
ans = f[size + 1];
delete []f;
return ans;
}