File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 시간복잡도: O(n)
3
+ * 실행속도: 65ms
4
+ * @param {string } s
5
+ * @return {number }
6
+ */
7
+ const numDecodings = function ( s ) {
8
+ const n = s . length ;
9
+
10
+ const memo = new Array ( n + 1 ) . fill ( 0 ) ;
11
+
12
+ function dfs ( i ) {
13
+ if ( i === n ) {
14
+ return 1 ;
15
+ }
16
+
17
+ if ( s [ i ] === "0" ) {
18
+ return 0 ;
19
+ }
20
+
21
+ if ( memo [ i ] ) {
22
+ return memo [ i ] ;
23
+ }
24
+
25
+ let res = dfs ( i + 1 ) ;
26
+
27
+ if ( i + 1 < n && Number ( s . slice ( i , i + 2 ) <= 26 ) ) {
28
+ res += dfs ( i + 2 ) ;
29
+ }
30
+
31
+ memo [ i ] = res ;
32
+
33
+ return res ;
34
+ }
35
+
36
+ return dfs [ 0 ] ;
37
+ } ;
38
+
39
+ /**
40
+ * 시간복잡도: O(n)
41
+ * 실행속도: 0~1ms
42
+ * @param {string } s
43
+ * @return {number }
44
+ */
45
+ /**
46
+ * 시간 복잡도: O(n)
47
+ * 공간 복잡도: O(n)
48
+ */
49
+ var numDecodings2 = function ( s ) {
50
+ const memo = new Map ( ) ;
51
+ memo . set ( s . length , 1 ) ;
52
+
53
+ function dfs ( start ) {
54
+ if ( memo . has ( start ) ) {
55
+ return memo . get ( start ) ;
56
+ }
57
+
58
+ if ( s [ start ] === "0" ) {
59
+ memo . set ( start , 0 ) ;
60
+ } else if (
61
+ start + 1 < s . length &&
62
+ parseInt ( s . slice ( start , start + 2 ) ) < 27
63
+ ) {
64
+ memo . set ( start , dfs ( start + 1 ) + dfs ( start + 2 ) ) ;
65
+ } else {
66
+ memo . set ( start , dfs ( start + 1 ) ) ;
67
+ }
68
+
69
+ return memo . get ( start ) ;
70
+ }
71
+
72
+ return dfs ( 0 ) ;
73
+ } ;
You can’t perform that action at this time.
0 commit comments