A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
解题思路:这道题可以拆分多个子问题然后相加计算出来,同时不同子问题又有重叠的情况,所以可以使用过动态规划,问题在于推导出递推公式,这里我将存储的数组定义为dp,字符串为s,dp[i]代表前i个字符可解码的数量,即dp[i]代表的是s[i-1]及之前字符的总解码数量。
时间复杂度:O(n)
空间复杂度:O(n)
很明显可知dp[i]的值与dp[i-1]、dp[i-2]都有关,当出现诸如s[i-1]='2'且s[i-2]='1'的情况时,dp[i]=dp[i-1]+dp[i-2],否则dp[i]=dp[i-1]。这里是因为“12”具有“1”+“2”和“12”两种解码方式,因此dp[i]=dp[i-1](代表s[i-1]='2'的情况,即只解码自己本身的情况)+ dp[i-2](代表s[i-1]='2'且s[i-2]='1'的情况,即解码自己加上上一个字符解码的情况)。除此之外,还需要注意当s[i-1]='0'时dp[i-1]=0的情况,因为s[i-1]='0'时它本身是不能进行解码的,因此dp[i-1]必须设为0,可以自己举个例子。
代码如下:
class Solution {
public:
int numDecodings(string s)
{
if(s[0] == '0')
return 0;
if(s.length() == 1)
return 1;
int len = s.length();
vector<int> dp(len+1, 0);
dp[0] = dp[1]= 1;
for(int i = 2; i <= len; i++)
{
if(s[i-1] == '0')
dp[i-1] = 0;
if(s[i-2] == '1' || s[i-2] == '2' && s[i-1] <= '6')
{
dp[i] = dp[i-1] + dp[i-2];
}
else
{
dp[i] = dp[i-1];
}
}
return dp[len];
}
};
类似题目: