Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6c10132

Browse files
[fix][typescript] house-robber-iii (labuladong#1406)
* [fix][typescript] house-robber-iii * [fix][javascript] house-robber-iii * [fix][javascript] house-robber-iii * [fix][javascript] house-robber-iii
1 parent bd55d15 commit 6c10132

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

‎多语言解法代码/solution_code.md

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28924,27 +28924,31 @@ class Solution {
2892428924
```javascript
2892528925
// by chatGPT (javascript)
2892628926
var rob = function(root) {
28927+
// memo 需要提到函数外侧,否则每次递归重新声明 memo,相当于备忘录没有生效
2892728928
const memo = new Map();
28928-
if (root === null) {
28929-
return 0;
28929+
let dp = (node) => {
28930+
if (node === null) {
28931+
return 0;
28932+
}
28933+
// 利用备忘录消除重叠子问题
28934+
if (memo.has(node)) {
28935+
return memo.get(node);
28936+
}
28937+
// 抢,然后去下下家
28938+
let do_it = node.val +
28939+
((node.left === null) ?
28940+
0 :
28941+
dp(node.left.left) + dp(node.left.right)) +
28942+
((node.right === null) ?
28943+
0 :
28944+
dp(node.right.left) + dp(node.right.right));
28945+
// 不抢,然后去下家
28946+
let not_do = dp(node.left) + dp(node.right);
28947+
let res = Math.max(do_it, not_do);
28948+
memo.set(node, res);
28949+
return res;
2893028950
}
28931-
// 利用备忘录消除重叠子问题
28932-
if (memo.has(root)) {
28933-
return memo.get(root);
28934-
}
28935-
// 抢,然后去下下家
28936-
let do_it = root.val +
28937-
((root.left === null) ?
28938-
0 :
28939-
rob(root.left.left) + rob(root.left.right)) +
28940-
((root.right === null) ?
28941-
0 :
28942-
rob(root.right.left) + rob(root.right.right));
28943-
// 不抢,然后去下家
28944-
let not_do = rob(root.left) + rob(root.right);
28945-
let res = Math.max(do_it, not_do);
28946-
memo.set(root, res);
28947-
return res;
28951+
return dp(root)
2894828952
};
2894928953
```
2895028954

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /