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));
}
}
本文探讨了一个基于二叉树结构的房屋抢劫问题,目标是在不触发报警的情况下,实现抢劫金额最大化。文章通过深度优先搜索(DFS)算法,详细解析了如何在给定的二叉树结构中,决定每间房屋是否进行抢劫,以达到最大收益。
423

被折叠的 条评论
为什么被折叠?



