您的位置:首页 > 其它

leetcode 91. Decode Ways

2014-12-16 21:16 459 查看
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.

[Solution]

分类讨论+动态规划.

int numDecodings(string s)
{
if (s.size() < 1 || s[0] == '0')
return 0;
vector<int> table(s.size() + 1, 1);

for (int i = 1; i < s.size(); i++)
{
if (s[i] == '0')
{
if (s[i - 1] == '1' || s[i - 1] == '2')
table[i + 1] = table[i - 1];
else
return 0;
}
else if (s[i] > '6')
{
if (s[i - 1] == '1')
table[i + 1] = table[i] + table[i - 1];
else
table[i + 1] = table[i];
}
else
{
if (s[i - 1] == '1' || s[i - 1] == '2')
table[i + 1] = table[i] + table[i - 1];
else
table[i + 1] = table[i];
}
}

return table[s.size()];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: