337. House Robber III

本文探讨了一个基于二叉树结构的房屋抢劫问题,目标是在不触发报警的情况下,实现抢劫金额最大化。文章通过深度优先搜索(DFS)算法,详细解析了如何在给定的二叉树结构中,决定每间房屋是否进行抢劫,以达到最大收益。
部署运行你感兴趣的模型镜像

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

相邻的两个房间如果同时被抢劫会报警,求能抢劫的最大金额。

DFS遍历,每个房间都可以选择抢或者不抢,如果抢的话,那么它两个子节点就不能抢。如果不抢的话,它的两个子节点可抢可不抢,选择最大的。

class Solution {
    public int doRob(TreeNode treeNode) {
        if (treeNode.left == null && treeNode.right == null) {
            return treeNode.val;
        }
        int maxLeft = 0;
        if (treeNode.left != null) {
            maxLeft = noRob(treeNode.left);
        }
        int maxRight = 0;
        if (treeNode.right != null) {
            maxRight = noRob(treeNode.right);
        }
        return treeNode.val + maxLeft + maxRight;
    }
    public int noRob(TreeNode treeNode) {
        if (treeNode.left == null && treeNode.right == null) {
            return 0;
        }
        int maxLeft = 0;
        if (treeNode.left != null) {
            maxLeft = Math.max(noRob(treeNode.left), doRob(treeNode.left));
        }
        int maxRight = 0;
        if (treeNode.right != null) {
            maxRight = Math.max(noRob(treeNode.right), doRob(treeNode.right));
        }
        return maxLeft + maxRight;
    }
    public int rob(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(doRob(root), noRob(root));
    }
}

 

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值