力扣-337打家劫舍III(dp)

力扣-337打家劫舍III

1、题目

337. 打家劫舍 III

小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root

除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。

给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。

示例 1:

img

输入: root = [3,2,3,null,3,null,1]
输出: 7 
解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 7

2、分析

  1. 题目。很明显,这是一个二叉树,那么我们能够想到,是前中后深度遍历,还是层序遍历。简化题目,假如只有三个节点,根左右,这里就有两种情况,一种就是要根节点,一种就是只要左右子节点。也就是把根节点单独拿出来,我们使用后序遍历很明显。
  2. 第一种就是直接递归,求解,但是会超时。我们这里可以使用一个map用来存计算某个节点后的值,用来避免一些重复计算。第二种就是使用技巧dp[2],dp[0]表示不选择该节点,dp[1]表示选择该节点。
  3. 因为左右要和根节点进行分离,所以,我们进行对是否要根节点进行值比较,选择大的就是我们需要的。

3、代码及分析

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        Map<TreeNode, Integer> map = new HashMap<>();
        int[] res = rob2(root);
        return Math.max(res[0], res[1]);
    }
    // 1. 第一种方式 递归 + 存值
    public int rob1(TreeNode root, Map<TreeNode, Integer> map){
        if (root == null) return 0;

        if (map.containsKey(root)){
            return map.get(root);
        }

        int money = root.val;
        
        if (root.left != null){
            money += rob1(root.left.left, map) + rob1(root.left.right, map);
        }
        if (root.right != null){
            money += rob1(root.right.left, map) + rob1(root.right.right, map);
        }
        map.put(root, Math.max(money, rob1(root.left, map) + rob1(root.right, map)));

        return Math.max(money, rob1(root.left, map) + rob1(root.right, map));
    }
    
    // 2.第二种方式 dp[2]
    public int[] rob2(TreeNode root){
        int[] res = new int[2];
        if (root == null) return res;

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

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

        return res;
    }

}

4、练习

力扣题目链接337. 打家劫舍 III

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值