Skip to content

Latest commit

 

History

History
83 lines (64 loc) · 2.45 KB

337. House Robber III.md

File metadata and controls

83 lines (64 loc) · 2.45 KB

337. House Robber III

https://leetcode.com/problems/house-robber-iii/

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

代码

  • 对于每个节点,我们希望获得的最大利润可以表示为:val = max(root.val + grandChild_val, leftChild.val + rightChild.val),意思是我有两种偷窃方案,要保证不能偷窃带有"父子关系"的点:偷窃当前节点以及孙子节点(左、右孙子偷窃总和),或者不偷当前节点,改为左孩子和右孩子的偷窃总和,然后比较哪个方案的偷窃值更高。
class Solution(object):
    def rob(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        hm = {}	# 存储节点的偷窃值
        return self.helper(root, hm)
        
    def helper(self, root, hm):
        if not root:    return 0
        if root in hm:  return hm.get(root)
        val = 0
        if root.left:
            val += self.helper(root.left.left, hm) + self.helper(root.left.right, hm)
        if root.right:
            val += self.helper(root.right.left, hm) + self.helper(root.right.right, hm)
        val = max(val + root.val, self.helper(root.left, hm) + self.helper(root.right, hm))
        hm[root] = val
        return val
  • Java
class Solution {
    public int rob(TreeNode root) {
        int[] res = dfs(root);
        return Math.max(res[0], res[1]);
    }
    
    private int[] dfs(TreeNode root) {
        if (root == null) return new int[] {0, 0};
        int[] left = dfs(root.left);
        int[] right = dfs(root.right);
        return new int[] {Math.max(left[0], left[1]) + Math.max(right[0], right[1]), left[0] + right[0] + root.val};
    }
}