LeetCode337. 打家劫舍3

题目描述

小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root。
除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。
给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。

涉及tag

二叉树-bfs

算法思路

方法1:
本题是一道动态规划的题目。把单个节点看做爷爷,它能获得最多的钱有两种途径,1自己的钱加上四个孙子的钱 2两个儿子的钱
最后比较这两种方式得到的钱大小返回。
方法2:
在计算爷爷节点抢了多少钱的时候,需要计算四个孙子节点抢的钱数,但是当父亲节点变成爷爷节点的时候,四个孙子变成儿子,产生重复计算。
所以把第一遍计算的结果存储起来可以省略计算步骤,实现时间优化。由于二叉树不适合用数组当做缓存,选用哈希表。
方法3:
每个节点都有两种状态,选择偷——状态result[0]还是不偷result[1]。

示例代码1

class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;
        int money = root.val;
        if (root.left != null)
        money += (rob(root.left.left) + rob(root.left.right));
        if (root.right != null)
        money += (rob(root.right.left) + rob(root.right.right));
        return Math.max(money, rob(root.left) + rob(root.right));
    }
}

超时

示例代码2

class Solution {
    HashMap<TreeNode, Integer> memory = new HashMap<>();
    public int rob(TreeNode root) {
        return robInternal(root, memory);
    }
    public int robInternal(TreeNode root, HashMap<TreeNode, Integer> memory) {
        if (root == null) return 0;
        //这里就是优化的地方,如果第一遍计算的这个节点能rob的值已经存放在哈希表,直接拿走返回,不需要重复计算
        if (memory.containsKey(root)) return memory.get(root);
        int money = root.val;
        if (root.left != null)
        money += (robInternal(root.left.left, memory) + robInternal(root.left.right, memory));
        if (root.right != null)
        money += (robInternal(root.right.left, memory) + robInternal(root.right.right, memory));
        int result = Math.max(money, robInternal(root.left, memory) + robInternal(root.right, memory));
        memory.put(root, result);
        return result;
    }
}

示例代码3

public int rob(TreeNode root) {
    int[] result = robInternal(root);
    return Math.max(result[0], result[1]);
}

public int[] robInternal(TreeNode root) {
    if (root == null) return new int[2];
    int[] result = new int[2];

    int[] left = robInternal(root.left);
    int[] right = robInternal(root.right);

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

    return result;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值