forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChaedie.py
57 lines (44 loc) Β· 1.13 KB
/
Chaedie.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
"""
dp λ¬Έμ λ μμ§ μ΄μν΄μ μ§μ νμ§ λͺ»νμ΅λλ€.
"""
"""
μ¬κ·μ dp hash_map μ νμ©ν μΊμ± μ λ΅
Time: O(n)
Space: O(n) = O(n) + O(n)
"""
class Solution:
def numDecodings(self, s: str) -> int:
dp = {len(s): 1}
def dfs(i):
if i in dp:
return dp[i]
if s[i] == "0":
return 0
# νμ리 μ«μ
res = dfs(i + 1)
# λμ리 μ«μ
if i + 1 < len(s) and (
s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456"
):
res += dfs(i + 2)
dp[i] = res
return res
return dfs(0)
"""
iterative dp
Time: O(n)
Space: O(n)
"""
class Solution:
def numDecodings(self, s: str) -> int:
dp = {len(s): 1}
for i in range(len(s) - 1, -1, -1):
if s[i] == "0":
dp[i] = 0
else:
dp[i] = dp[i + 1]
if i + 1 < len(s) and (
s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456"
):
dp[i] += dp[i + 2]
return dp[0]