Leetcode 91
This is a 1-d DP. Set dp[i] to be the decode ways for s[:i+1]
, we have:
dp[i]=dp[i−2]⋅Mi1+dp[i−1]⋅Mi2
In which,
Mi1Mi2=∣{S[i]∈A1}∣=∣{S[i−1:i+1]∈A2}
- Mi1 means how many ways to match the 1-character decoders A1 with S[i]. In this problem we have either 1(S[i]∈A1) or 0(not match, or not exists)
- Mi2 means how many ways to match the 2-character decoders A2 with S[i−1:i+1]. In this problem we have either 1(S[i]∈A1) or 0(not match, or not exists)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Solution:
def numDecodings(self, s: str) -> int:
one = {str(k):1 for k in range(1, 10)}
two = {str(k):1 for k in range(10, 27)}
dp = [0]*len(s)
for i in range(len(s)):
match_one = one.get(s[i], 0)
match_two = two.get(s[i-1:i+1], 0) if i-1>=0 else 0
one_bit = dp[i-1]*match_one if i-1>=0 else match_one
two_bit = dp[i-2]*match_two if i-2>=0 else match_two
dp[i] = one_bit + two_bit
return dp[-1]
|
Notes
- Use
get()
to take care of cases when s[i]
is not in one
- Take care of the corner cases when i<=2, in which we can’t get dp values.
- Follow Up: Decode Ways 2