-
Notifications
You must be signed in to change notification settings - Fork 17
/
decode-ways-ii.py
65 lines (51 loc) · 1.98 KB
/
decode-ways-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from functools import lru_cache
class Solution:
def numDecodings(self, encoded: str) -> int:
MOD = 10 ** 9 + 7
def get_number_of_options(pos: int, length: int) -> int:
if length == 1:
if encoded[pos] == "*":
return 9
elif encoded[pos] == "0":
return 0
else:
return 1
elif length == 2 and pos + length <= len(encoded):
if encoded[pos:pos + 2] == "**":
return 15
elif encoded[pos] == "*":
second_digit = int(encoded[pos + 1])
count = 0
for first_digit in range(1, 10):
if 9 < first_digit * 10 + second_digit < 27:
count += 1
return count
elif encoded[pos + 1] == "*":
first_digit = int(encoded[pos])
count = 0
for second_digit in range(1, 10):
if 9 < first_digit * 10 + second_digit < 27:
count += 1
return count
elif 9 < int(encoded[pos:pos + 2]) < 27:
return 1
return 0
@lru_cache(None)
def dp(pos: int) -> int:
if pos >= len(encoded):
return 1
return (
dp(pos + 1) * get_number_of_options(pos, 1) +
dp(pos + 2) * get_number_of_options(pos, 2)
) % MOD
def dp_bottom_up() -> int:
dp_prev, dp_prev_prev = 1, 0
for pos in reversed(range(len(encoded))):
dp = (
dp_prev * get_number_of_options(pos, 1) +
dp_prev_prev * get_number_of_options(pos, 2)
) % MOD
dp_prev, dp_prev_prev = dp, dp_prev
return dp
# return dp(0)
return dp_bottom_up()