Skip to content

feat:add LeetCode337 java solution code. #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions solution/0300-0399/0337.House Robber III/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,33 @@
<!-- 这里可写当前语言的特殊实现逻辑 -->

```java
class Solution {
//这里f(o)表示选择o节点的最大权重和
//这里g(o)表示不选择o节点最大权重和

//f(o) = g(o.left) + g(o.right) 因为选择了o节点,他的两个子节点就不可以选择
//g(0) = Math.max(f(o.left),g(o.left)) + Math.max(f(o.right),g(o.right)) 不选择o节点,他的子节点可选择,也可不选择
Map<TreeNode, Integer> f = new HashMap<>();
Map<TreeNode, Integer> g = new HashMap<>();

public int rob(TreeNode root) {
dfs(root);
return Math.max(f.getOrDefault(root, 0), g.getOrDefault(root, 0));
}

private void dfs(TreeNode root) {
if (root == null) {
return;
}

dfs(root.left);
dfs(root.right);

//选择了root,所以求和的时候要把root.val算进去
f.put(root, root.val + g.getOrDefault(root.left, 0) + g.getOrDefault(root.right, 0));
g.put(root, Math.max(f.getOrDefault(root.left, 0), g.getOrDefault(root.left, 0)) + Math.max(f.getOrDefault(root.right, 0), g.getOrDefault(root.right, 0)));
}
}

```

Expand Down