Source: https://leetcode.com/problems/decode-ways/
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
d
p
[
i
]
dp[i]
dp[i]表示
[
0...
i
]
[0...i]
[0...i]解码方法数,全部初始化0,对于
i
≥
2
i\geq 2
i≥2
d
p
[
i
]
+
=
{
d
p
[
i
−
1
]
s[i]不是0
d
p
[
i
−
2
]
s[i-1]s[i]在10到26之间
dp[i]+=\begin{cases} dp[i-1]& \text{s[i]不是0}\\ dp[i-2]& \text{s[i-1]s[i]在10到26之间} \end{cases}
dp[i]+={dp[i−1]dp[i−2]s[i]不是0s[i-1]s[i]在10到26之间
边界
i
=
=
0
i==0
i==0
d
p
[
i
]
+
=
{
1
s[i]不是0
0
s[i]是0
dp[i]+=\begin{cases} 1& \text{s[i]不是0}\\ 0& \text{s[i]是0} \end{cases}
dp[i]+={10s[i]不是0s[i]是0
i
=
=
1
i==1
i==1
d
p
[
i
]
+
=
{
d
p
[
i
−
1
]
s[i]不是0
1
s[i-1]s[i]在10到26之间
dp[i]+=\begin{cases} dp[i-1]& \text{s[i]不是0}\\ 1& \text{s[i-1]s[i]在10到26之间} \end{cases}
dp[i]+={dp[i−1]1s[i]不是0s[i-1]s[i]在10到26之间
class Solution {
public:
int numDecodings(string s) {
int n=s.length();
if(n==0)
return 0;
vector<int> dp(n,0);
if(s[0]=='0')
dp[0]=0;
else
dp[0]=1;
if(n==1)
return dp[0];
for(int i=1;i<n;i++){
if((s[i-1]-'0')*10+s[i]-'0'>=10 && (s[i-1]-'0')*10+s[i]-'0'<=26){
if(i>1)
dp[i]+=dp[i-2];
else
dp[i]+=1;
}
if(s[i]!='0'){
dp[i]+=dp[i-1];
}
}
return dp[n-1];
}
};