Skip to content

Commit 0672aae

Browse files
committed
feat: add ts solution to lc problem: No.0746
1 parent 0620cfb commit 0672aae

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

solution/0700-0799/0746.Min Cost Climbing Stairs/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,4 +266,34 @@ impl Solution {
266266

267267
<!-- solution:end -->
268268

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+
269299
<!-- problem:end -->

solution/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,4 +264,34 @@ impl Solution {
264264

265265
<!-- solution:end -->
266266

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+
267297
<!-- problem:end -->
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
}

0 commit comments

Comments
 (0)