File tree Expand file tree Collapse file tree 3 files changed +75
-0
lines changed
solution/0700-0799/0746.Min Cost Climbing Stairs Expand file tree Collapse file tree 3 files changed +75
-0
lines changed Original file line number Diff line number Diff line change @@ -266,4 +266,34 @@ impl Solution {
266
266
267
267
<!-- solution: end -->
268
268
269
+ <!-- solution: start -->
270
+
271
+ ### Solution 3: Dynamic Programming. Recursion and top-down approach
272
+
273
+ <!-- tabs: start -->
274
+
275
+ #### TypeScript
276
+
277
+ ``` ts
278
+ function minCostClimbingStairs(cost : number []): number {
279
+ const n = cost .length ;
280
+ const cache = Array (n ).fill (- 1 );
281
+
282
+ const fn = (i : number ): number => {
283
+ if (i <= 1 ) return cost [i ];
284
+ if (cache [i ] !== undefined && cache [i ] !== - 1 ) return cache [i ];
285
+
286
+ cache [i ] = (cost [i ] ?? 0 ) + Math .min (fn (i - 1 ), fn (i - 2 ));
287
+
288
+ return cache [i ];
289
+ };
290
+
291
+ return fn (n );
292
+ }
293
+ ```
294
+
295
+ <!-- tabs: end -->
296
+
297
+ <!-- solution: end -->
298
+
269
299
<!-- problem: end -->
Original file line number Diff line number Diff line change @@ -264,4 +264,34 @@ impl Solution {
264
264
265
265
<!-- solution: end -->
266
266
267
+ <!-- solution: start -->
268
+
269
+ ### Solution 3: Dynamic Programming. Recursion and top-down approach
270
+
271
+ <!-- tabs: start -->
272
+
273
+ #### TypeScript
274
+
275
+ ``` ts
276
+ function minCostClimbingStairs(cost : number []): number {
277
+ const n = cost .length ;
278
+ const cache = Array (n ).fill (- 1 );
279
+
280
+ const fn = (i : number ): number => {
281
+ if (i <= 1 ) return cost [i ];
282
+ if (cache [i ] !== undefined && cache [i ] !== - 1 ) return cache [i ];
283
+
284
+ cache [i ] = (cost [i ] ?? 0 ) + Math .min (fn (i - 1 ), fn (i - 2 ));
285
+
286
+ return cache [i ];
287
+ };
288
+
289
+ return fn (n );
290
+ }
291
+ ```
292
+
293
+ <!-- tabs: end -->
294
+
295
+ <!-- solution: end -->
296
+
267
297
<!-- problem: end -->
Original file line number Diff line number Diff line change
1
+ function minCostClimbingStairs ( cost : number [ ] ) : number {
2
+ const n = cost . length ;
3
+ const cache = Array ( n ) . fill ( - 1 ) ;
4
+
5
+ const fn = ( i : number ) : number => {
6
+ if ( i <= 1 ) return cost [ i ] ;
7
+ if ( cache [ i ] !== undefined && cache [ i ] !== - 1 ) return cache [ i ] ;
8
+
9
+ cache [ i ] = ( cost [ i ] ?? 0 ) + Math . min ( fn ( i - 1 ) , fn ( i - 2 ) ) ;
10
+
11
+ return cache [ i ] ;
12
+ } ;
13
+
14
+ return fn ( n ) ;
15
+ }
You can’t perform that action at this time.
0 commit comments