题目链接
【题目】
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.
【解析】
采用动态规划的方法。
网上有空间复杂度为O(n)的做法比如:
class Solution {
public:
int numDecodings(string s) {
if (s.empty() || (s.size() > 1 && s[0] == '0')) return 0;
vector<int> dp(s.size() + 1, 0);
dp[0] = 1;
for (int i = 1; i < dp.size(); ++i) {
dp[i] = (s[i - 1] == '0') ? 0 : dp[i - 1];
if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) {
dp[i] += dp[i - 2];
}
}
return dp.back();
}
};
这里采用一种空间复杂度为O(1)的方法(AC)【很快】:
两个变量p1,p2
初始为1
1)当s[i]==’0’时候,p1 = 0
2)当s[i] !=’0’时候,则当s[i-1]==’1’或者s[i-1]==’2’且s[i-1]<=’6’时候,p1 = p1 + p2(相当于加上前面的总数,p2记录上一次的总数)
p2 = p1 - p2(其实就是p2等于之前的p1)
3)否则,p2 = p1
class Solution {
public:
int numDecodings(string s) {
if(s[0] == '0' || s.length() == 0) return 0;
int p1=1,p2=1;
for(int i=1;i<s.length();i++){
if(s[i] == '0') p1 = 0;
if(s[i-1] == '1' || s[i-1] == '2' && s[i] <= '6'){
p1 = p2 + p1;
p2 = p1 - p2;
}
else p2 = p1;
}
return p1;
}
};
python
(1)
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) is 0:
return 0
dp = [1] + [0]*len(s)
for i in range(1,len(s)+1):
dp[i] = 0 if s[i-1]=='0' else dp[i-1]
dp[i] += dp[i-2] if (i>1 and (s[i-2]=='1' or (s[i-2] == '2' and s[i-1] <= '6'))) else 0
return dp[len(s)]
(2)
class Solution(object):
def numDecodings(self, s):
if (len(s) == 0 or s[0] == '0'):
return 0
p1 = 1
p2 = 1
for i in range(1,len(s)):
if s[i] == '0':
p1 = 0
if s[i-1] == '1' or (s[i-1] == '2' and s[i] <= '6'):
p1 = p1 + p2
p2 = p1 - p2
else:
p2 = p1
return p1