From 5865faa73a9a33fab1e199bbce96c29f508a378d Mon Sep 17 00:00:00 2001 From: Jack <965555169@qq.com> Date: Thu, 5 Aug 2021 10:36:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0337.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8D=20III-=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92-J?= =?UTF-8?q?avaScript=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0337.打家劫舍III.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index 197841e9..780e4aef 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -368,7 +368,32 @@ class Solution: return (val1, val2) ``` -Go: +JavaScript: + +> 动态规划 + +```javascript +const rob = root => { + // 后序遍历函数 + const postOrder = node => { + // 递归出口 + if (!node) return [0, 0]; + // 遍历左子树 + const left = postOrder(node.left); + // 遍历右子树 + const right = postOrder(node.right); + // 不偷当前节点,左右子节点都可以偷或不偷,取最大值 + const DoNot = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); + // 偷当前节点,左右子节点只能不偷 + const Do = node.val + left[0] + right[0]; + // [不偷,偷] + return [DoNot, Do]; + }; + const res = postOrder(root); + // 返回最大值 + return Math.max(...res); +}; +```