File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ dp 문제는 아직 어색해서 직접 풀진 못했습니다.
3
+ """
4
+
5
+ """
6
+ 재귀와 dp hash_map 을 활용한 캐싱 전략
7
+ Time: O(n)
8
+ Space: O(n) = O(n) + O(n)
9
+ """
10
+
11
+
12
+ class Solution :
13
+ def numDecodings (self , s : str ) -> int :
14
+ dp = {len (s ): 1 }
15
+
16
+ def dfs (i ):
17
+ if i in dp :
18
+ return dp [i ]
19
+ if s [i ] == "0" :
20
+ return 0
21
+
22
+ # 한자리 숫자
23
+ res = dfs (i + 1 )
24
+
25
+ # 두자리 숫자
26
+ if i + 1 < len (s ) and (
27
+ s [i ] == "1" or s [i ] == "2" and s [i + 1 ] in "0123456"
28
+ ):
29
+ res += dfs (i + 2 )
30
+ dp [i ] = res
31
+ return res
32
+
33
+ return dfs (0 )
34
+
35
+
36
+ """
37
+ iterative dp
38
+ Time: O(n)
39
+ Space: O(n)
40
+ """
41
+
42
+
43
+ class Solution :
44
+ def numDecodings (self , s : str ) -> int :
45
+ dp = {len (s ): 1 }
46
+
47
+ for i in range (len (s ) - 1 , - 1 , - 1 ):
48
+ if s [i ] == "0" :
49
+ dp [i ] = 0
50
+ else :
51
+ dp [i ] = dp [i + 1 ]
52
+
53
+ if i + 1 < len (s ) and (
54
+ s [i ] == "1" or s [i ] == "2" and s [i + 1 ] in "0123456"
55
+ ):
56
+ dp [i ] += dp [i + 2 ]
57
+ return dp [0 ]
You can’t perform that action at this time.
0 commit comments