File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * [Problem]: [91] Decode Ways
3+ *
4+ * (https://leetcode.com/problems/decode-ways/description/)
5+ */
6+ function numDecodings ( s : string ) : number {
7+ //시간복잡도 O(n)
8+ //공간복잡도 O(n)
9+ function memoizationFunc ( s : string ) : number {
10+ const memoization : Record < number , number > = { } ;
11+
12+ function dfs ( index : number ) : number {
13+ if ( index in memoization ) return memoization [ index ] ;
14+ if ( index === s . length ) return 1 ;
15+ if ( s [ index ] === "0" ) return 0 ;
16+
17+ let result = dfs ( index + 1 ) ;
18+ if ( index + 1 < s . length && + s . slice ( index , index + 2 ) <= 26 ) {
19+ result += dfs ( index + 2 ) ;
20+ }
21+
22+ memoization [ index ] = result ;
23+ return result ;
24+ }
25+
26+ return dfs ( 0 ) ;
27+ }
28+
29+ //시간복잡도 O(n)
30+ //공간복잡도 O(1)
31+ function optimizedFunc ( s : string ) : number {
32+ let prev2 = 1 ;
33+ let prev1 = s [ 0 ] === "0" ? 0 : 1 ;
34+
35+ for ( let i = 1 ; i < s . length ; i ++ ) {
36+ let curr = 0 ;
37+
38+ const one = + s . slice ( i , i + 1 ) ;
39+ const two = + s . slice ( i - 1 , i + 1 ) ;
40+
41+ if ( one >= 1 && one <= 9 ) curr += prev1 ;
42+ if ( two >= 10 && two <= 26 ) curr += prev2 ;
43+
44+ prev2 = prev1 ;
45+ prev1 = curr ;
46+ }
47+
48+ return prev1 ;
49+ }
50+ return optimizedFunc ( s ) ;
51+ }
You can’t perform that action at this time.
0 commit comments