337. House Robber III

栏目: 数据库 · 发布时间: 6年前

内容简介: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 plac

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.

难度:medium

题目:

小偷又发现了一个新的地方来实施的偷盗计划。 这个地方只有一个入口叫“根”。除了这个根之外,每个房间有且仅有一个父房间。一番游览过后,聪明的小偷意识到这里所有的房子形成了一棵二叉树。如果在同一晚上有任何两个相邻的房子遭遇偷盗就会触发警报。

在这个晚上小偷如何决策在不触发警报的情况下获取最大的盗资。

思路:

二叉树遍历

Runtime: 733 ms, faster than 27.11% of Java online submissions for House Robber III.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    // rob root,     g(root)     = root.val + f(root.left.left) + f(root.left.right) + f(root.right.left) + f(root.right.right)
    // not rob root, g(not_root) = f(root.left) + f(root.right);
    // f(root) = Math.max(g(root), g(not_root))
    
    public int rob(TreeNode root) {
        if (null == root) {
            return 0;
        }

        TreeNode left = root.left;
        int leftSum = (null == left) ? 0 : (rob(left.left) + rob(left.right));
        
        TreeNode right = root.right;
        int rightSum = (null == right) ? 0 : (rob(right.left) + rob(right.right));
        
        return Math.max(root.val + leftSum + rightSum, rob(left) + rob(right));
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

赢在用户

赢在用户

[美]Steve Mulder、[美]Zivv Yarr / 范晓燕 / 机械工业出版社 / 2007-08-01 / 29.00

您如何保证您的网站确实给予用户他们所需要的,并对您产生商业成果?您需要了解谁是您的用户,您的用户的目标、行为和观点是什么,还要把他们的需求当成您的第一要务。人物角色将用户研究带入了一个更高的境界,成为实施真正以用户为中心的在线商业策略最高效的工具。本书将伴随您走过创建人物角色的每一个步骤,包括进行定性、定量的用户研究,生成人物角色分类,使人物角色真实可信等。您也将学会如何有效地通过这个工具,来完成......一起来看看 《赢在用户》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

html转js在线工具
html转js在线工具

html转js在线工具