Leetcode 337. House Robber III

22 篇文章 0 订阅
20 篇文章 0 订阅

Naive solution. There are many overlapping sub problems.

e.g. if we rob(root), we need to know rob(left), rob(right), rob(left.left), rob(left.right), ...

then, say if we want to rob(root.left), the algorithm below calculates rob(left.left), rob(left.right) again.

/**
 * There are two choices, rob root house or skip the root house.
 * Take the maximum of the two choices. 
 * If we choose to rob the root, then we cannot rob the left and right child of the root.
 * robRoot = root.val + root.left.left + root.left.right + root.right.left + root.right.right
 * If we choose not to rob the root, 
 * robNoRoot = root.left + root.right
 * Then take the maximum as profit,
 * money = max(robRoot, robNoRoot)
 */ 
public class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;
        int robRoot = root.val;
        
        // rob the root house
        if (root.left != null) {
            robRoot += rob(root.left.left) + rob(root.left.right);
        }
        if (root.right != null) {
            robRoot += rob(root.right.left) + rob(root.right.right);
        }
        
        return Math.max(robRoot, rob(root.left)+rob(root.right));
    }
}
Using a hashmap to save the result for every root so that we can avoid duplicate calculating.

public class Solution {
    public int rob(TreeNode root) {
        return helper(root, new HashMap<>());
    }
    
    public static int helper(TreeNode r, HashMap<TreeNode, Integer> map) {
        if (r == null) return 0;
        if (map.containsKey(r)) return map.get(r);
        
        int robRoot = r.val;
        
        // rob the root house
        if (r.left != null)
            robRoot += helper(r.left.left, map) + helper(r.left.right, map);
        if (r.right != null)
            robRoot += helper(r.right.left, map) + helper(r.right.right, map);
            
        int money = Math.max(robRoot, helper(r.left, map) + helper(r.right, map));
        map.put(r, money);
        
        return money;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值