File tree Expand file tree Collapse file tree 3 files changed +99
-0
lines changed
solution/0100-0199/0198.House Robber Expand file tree Collapse file tree 3 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -254,4 +254,42 @@ function rob(nums: number[]): number {
254
254
255
255
<!-- solution: end -->
256
256
257
+ <!-- solution: start -->
258
+
259
+ ### Solution 3: Dynamic Programming, top-down approach
260
+
261
+ <!-- tabs: start -->
262
+
263
+ #### TypeScript
264
+
265
+ ``` ts
266
+ export function rob(nums : number []): number {
267
+ const cache: Record <number , number > = {};
268
+ const n = nums .length ;
269
+ let ans = 0 ;
270
+
271
+ const dp = (i : number ) => {
272
+ if (cache [i ] !== undefined ) return cache [i ];
273
+
274
+ let max = 0 ;
275
+ for (let j = i + 2 ; j < n ; j ++ ) {
276
+ max = Math .max (max , dp (j ));
277
+ }
278
+ cache [i ] = max + nums [i ];
279
+
280
+ return cache [i ];
281
+ };
282
+
283
+ for (let i = 0 ; i < n ; i ++ ) {
284
+ ans = Math .max (ans , dp (i ));
285
+ }
286
+
287
+ return ans ;
288
+ }
289
+ ```
290
+
291
+ <!-- tabs: end -->
292
+
293
+ <!-- solution: end -->
294
+
257
295
<!-- problem: end -->
Original file line number Diff line number Diff line change @@ -253,4 +253,42 @@ function rob(nums: number[]): number {
253
253
254
254
<!-- solution: end -->
255
255
256
+ <!-- solution: start -->
257
+
258
+ ### Solution 3: Dynamic Programming, top-down approach
259
+
260
+ <!-- tabs: start -->
261
+
262
+ #### TypeScript
263
+
264
+ ``` ts
265
+ export function rob(nums : number []): number {
266
+ const cache: Record <number , number > = {};
267
+ const n = nums .length ;
268
+ let ans = 0 ;
269
+
270
+ const dp = (i : number ) => {
271
+ if (cache [i ] !== undefined ) return cache [i ];
272
+
273
+ let max = 0 ;
274
+ for (let j = i + 2 ; j < n ; j ++ ) {
275
+ max = Math .max (max , dp (j ));
276
+ }
277
+ cache [i ] = max + nums [i ];
278
+
279
+ return cache [i ];
280
+ };
281
+
282
+ for (let i = 0 ; i < n ; i ++ ) {
283
+ ans = Math .max (ans , dp (i ));
284
+ }
285
+
286
+ return ans ;
287
+ }
288
+ ```
289
+
290
+ <!-- tabs: end -->
291
+
292
+ <!-- solution: end -->
293
+
256
294
<!-- problem: end -->
Original file line number Diff line number Diff line change
1
+ export function rob ( nums : number [ ] ) : number {
2
+ const cache : Record < number , number > = { } ;
3
+ const n = nums . length ;
4
+ let ans = 0 ;
5
+
6
+ const dp = ( i : number ) => {
7
+ if ( cache [ i ] !== undefined ) return cache [ i ] ;
8
+
9
+ let max = 0 ;
10
+ for ( let j = i + 2 ; j < n ; j ++ ) {
11
+ max = Math . max ( max , dp ( j ) ) ;
12
+ }
13
+ cache [ i ] = max + nums [ i ] ;
14
+
15
+ return cache [ i ] ;
16
+ } ;
17
+
18
+ for ( let i = 0 ; i < n ; i ++ ) {
19
+ ans = Math . max ( ans , dp ( i ) ) ;
20
+ }
21
+
22
+ return ans ;
23
+ }
You can’t perform that action at this time.
0 commit comments