File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * [Problem]: [198] House Robber
3
+ * (https://leetcode.com/problems/house-robber/description/)
4
+ */
5
+ function rob ( nums : number [ ] ) : number {
6
+ // 시간 복잡도 O(2^n)
7
+ // 공간 복잡도 O(n)
8
+ // 시간 초과
9
+ function recursionFunc ( nums : number [ ] ) : number {
10
+ function getMax ( start : number ) : number {
11
+ if ( nums . length - 1 < start ) return 0 ;
12
+ return Math . max ( nums [ start ] + getMax ( start + 2 ) , getMax ( start + 1 ) ) ;
13
+ }
14
+
15
+ return getMax ( 0 ) ;
16
+ }
17
+
18
+ // 메모이제이션
19
+ // 시간복잡도 O(n)
20
+ // 공간복잡도 O(n)
21
+ function memoizationFunc ( nums : number [ ] ) : number {
22
+ let memoArr = new Array ( nums . length ) . fill ( - 1 ) ;
23
+ function getMax ( start : number ) : number {
24
+ if ( nums . length - 1 < start ) return 0 ;
25
+ if ( memoArr [ start ] !== - 1 ) return memoArr [ start ] ;
26
+
27
+ memoArr [ start ] = Math . max ( nums [ start ] + getMax ( start + 2 ) , getMax ( start + 1 ) ) ;
28
+
29
+ return memoArr [ start ] ;
30
+ }
31
+
32
+ return getMax ( 0 ) ;
33
+ }
34
+
35
+ // DP
36
+ // 시간복잡도 O(n)
37
+ // 공간복잡도 O(1)
38
+ function dpSolution ( nums : number [ ] ) : number {
39
+ if ( nums . length === 1 ) return nums [ 0 ] ;
40
+
41
+ let prev2 = 0 ;
42
+ let prev1 = 0 ;
43
+
44
+ for ( let num of nums ) {
45
+ let current = Math . max ( prev1 , prev2 + num ) ;
46
+ prev2 = prev1 ;
47
+ prev1 = current ;
48
+ }
49
+
50
+ return prev1 ;
51
+ }
52
+
53
+ return dpSolution ( nums ) ;
54
+ }
You can’t perform that action at this time.
0 commit comments