diff --git a/problems/0337.打家劫舍III.md b/problems/0337.打家劫舍III.md index 0a4b752b..3504a574 100644 --- a/problems/0337.打家劫舍III.md +++ b/problems/0337.打家劫舍III.md @@ -287,24 +287,85 @@ class Solution { Python: -> 动态规划 -```python +> 暴力递归 + +```python3 + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def rob(self, root: TreeNode) -> int: - result = self.robTree(root) + if root is None: + return 0 + if root.left is None and root.right is None: + return root.val + # 偷父节点 + val1 = root.val + if root.left: + val1 += self.rob(root.left.left) + self.rob(root.left.right) + if root.right: + val1 += self.rob(root.right.left) + self.rob(root.right.right) + # 不偷父节点 + val2 = self.rob(root.left) + self.rob(root.right) + return max(val1, val2) +``` + +> 记忆化递归 + +```python3 + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + memory = {} + def rob(self, root: TreeNode) -> int: + if root is None: + return 0 + if root.left is None and root.right is None: + return root.val + if self.memory.get(root) is not None: + return self.memory[root] + # 偷父节点 + val1 = root.val + if root.left: + val1 += self.rob(root.left.left) + self.rob(root.left.right) + if root.right: + val1 += self.rob(root.right.left) + self.rob(root.right.right) + # 不偷父节点 + val2 = self.rob(root.left) + self.rob(root.right) + self.memory[root] = max(val1, val2) + return max(val1, val2) +``` + +> 动态规划 +```python3 +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rob(self, root: TreeNode) -> int: + result = self.rob_tree(root) return max(result[0], result[1]) - #长度为2的数组,0:不偷,1:偷 - def robTree(self, cur): - if not cur: - return (0, 0) #这里返回tuple, 也可以返回list - left = self.robTree(cur.left) - right = self.robTree(cur.right) - #偷cur - val1 = cur.val + left[0] + right[0] - #不偷cur - val2 = max(left[0], left[1]) + max(right[0], right[1]) - return (val2, val1) + def rob_tree(self, node): + if node is None: + return (0, 0) # (偷当前节点金额,不偷当前节点金额) + left = self.rob_tree(node.left) + right = self.rob_tree(node.right) + val1 = node.val + left[1] + right[1] # 偷当前节点,不能偷子节点 + val2 = max(left[0], left[1]) + max(right[0], right[1]) # 不偷当前节点,可偷可不偷子节点 + return (val1, val2) ``` Go: