Skip to content

Commit 38fed5d

Browse files
committed
feat: add ts solution to lc problem: No.0198
1 parent 0620cfb commit 38fed5d

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed

solution/0100-0199/0198.House Robber/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,4 +254,42 @@ function rob(nums: number[]): number {
254254

255255
<!-- solution:end -->
256256

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

solution/0100-0199/0198.House Robber/README_EN.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,4 +253,42 @@ function rob(nums: number[]): number {
253253

254254
<!-- solution:end -->
255255

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

0 commit comments

Comments
 (0)