leetcode337 打家劫舍3

https://leetcode-cn.com/problems/house-robber-iii/
使用递归就能解决。区分为两种情况:当前节点用还是不用。

class Solution {
    public int rob(TreeNode root) {
        if(root == null){
            return 0;
        }

        // rob root
        int res1 = root.val;
        if(root.left != null){
            res1 += rob(root.left.left) + rob(root.left.right);
        }
        if(root.right != null){
            res1 += rob(root.right.left) + rob(root.right.right);
        }

        //not rob root
        int res2 = rob(root.left) + rob(root.right);
        return Math.max(res1, res2);
    }
}

这种做法会超时,主要原因是存在大量的重复计算。比如:
3
/
2 3
\ \
3 1
在这种情况,抢劫根节点3的时候,需要计算抢不抢叶节点3和1的情况。那么在不抢劫根节点3的时候,直接计算节点2和3,那么此时存在强不强的两种情况,如果不强的时候,那么叶节点3和1就又重复计算了。
如何解决这个问题呢,那么可以用map来进行存储。把一些计算过的节点记录进map里。

class Solution {
    public int rob(TreeNode root){
        if(root == null){
            return 0;
        }
        HashMap<TreeNode, Integer> map = new HashMap<>();
        return help(root,map);
    }
    public int help(TreeNode root, HashMap<TreeNode, Integer> map) {
        if(root == null){
            return 0;
        }
        if(map.containsKey(root)) return map.get(root);

        // rob root
        int res1 = root.val;
        if(root.left != null){
            res1 += help(root.left.left,map) + help(root.left.right,map);
        }
        if(root.right != null){
            res1 += help(root.right.left,map) + help(root.right.right,map);
        }

        //not rob root
        int res2 = help(root.left,map) + help(root.right,map);
        int res = Math.max(res1, res2);
        map.put(root, res);
        return res;
    }
}

如果map中存在,那么直接取出返回。如果不存在,那么就计算,把计算完的数值记录在map中。

此题也可用动态规划来解决。动态规划的核心就是根据当前状态做出下一步的选择,无需关注是怎么达到当前状态的(也就是无后效性)。经过上面的递归,整个过程是一个调用栈。也就是相当于需要从叶节点开始做选择,进而一步步的向上推进。那么每一步其实都有两个状态,那就是选和不选。所以用一个数组来进行状态的存储。

class Solution {
    public int rob(TreeNode root){
        int[] res = help(root);
        return Math.max(res[0],res[1]);
    }

    public int[] help(TreeNode root) {
        //res[0] : 不选 不rob
        //res[1] : 选 rob
        int[] res = new int[2];
        if(root == null){
            return res;
        }
        
        int[] left = help(root.left);
        int[] right = help(root.right);

        res[0] = 0 + Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
        res[1] = root.val + left[0] + right[0];

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值