题目
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.
分析
Dynamic Programming ,即为动态规划。
一般的解题思路是模拟 ==斐波那契数列==,或者类似 ==爬梯子问题==,即位置i的的组合个数仅仅依赖于i-1 和i-2的组合个数
时间复杂度O(n),空间复杂度O(n)
注意 ‘0’ 不能当首字符出现,允许的情况只有’10’,’20’这种情况。
动态规划的题目我基本上还没有涉及到过,这种题碰到还没有思路。
实现
class Solution {
public:
int numDecodings(string s) {
if (s == "" || (s.length() > 0 && s[0] == '0'))
return 0;
vector<int> number (s.length() + 1,0);
number[0] = 1;
number[1] = 1;
for (int i = 2; i <= s.length(); i++)
{
//当前面一位数字在1-9之间时
if (s[i-1] != '0')
number[i] = number[i - 1];
// 当前面两位数字在10-26之间时
if (i>1 && s[i - 2] != '0')
{
if ((s[i - 2] == '1' ||( s[i - 2] == '2'&&s[i - 1] <= '6')))
number[i] += number[i - 2];
}
}
return number[s.length()];
}
};