diff --git a/problems/337.house-robber-iii.md b/problems/337.house-robber-iii.md index dbe0ad654..5adc21a58 100644 --- a/problems/337.house-robber-iii.md +++ b/problems/337.house-robber-iii.md @@ -63,7 +63,7 @@ https://leetcode-cn.com/problems/house-robber-iii/ ## 代码 -语言支持:JS, Python +语言支持:JS, C++,Java,Python JavaScript Code: @@ -89,6 +89,78 @@ var rob = function (root) { }; ``` +C++ Code: +```c++ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int rob(TreeNode* root) { + pair res = dfs(root); + return max(res.first, res.second); + } + + pair dfs(TreeNode* root) + { + pair res = {0, 0}; + if(root == NULL) + { + return res; + } + + pair left = dfs(root->left); + pair right = dfs(root->right); + // 0 代表不偷,1 代表偷 + res.first = max(left.first, left.second) + max(right.first, right.second); + res.second = left.first + right.first + root->val; + return res; + } + +}; +``` + +Java Code: +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int rob(TreeNode root) { + int[] res = dfs(root); + return Math.max(res[0], res[1]); + } + + public int[] dp(TreeNode root) + { + int[] res = new int[2]; + if(root == null) + { + return res; + } + + int[] left = dfs(root.left); + int[] right = dfs(root.right); + // 0 代表不偷,1 代表偷 + res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); + res[1] = left[0] + right[0] + root.val; + return res; + } +} +``` + Python Code: ```python