zoukankan      html  css  js  c++  java
  • [LintCode] 535. House Robber III

    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

    Example1

    Input:  {3,2,3,#,3,#,1}
    Output: 7
    Explanation:
    Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
      3
     / 
    2   3
         
      3   1
    

    Example2

    Input:  {3,4,5,1,3,#,1}
    Output: 9
    Explanation:
    Maximum amount of money the thief can rob = 4 + 5 = 9.
        3
       / 
      4   5
     /     
    1   3   1


    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: The maximum amount of money you can rob tonight
         */
        public int houseRobber3(TreeNode root) {
            // write your code here
            ResType res = helper(root);
            return Math.max(res.rob, res.notRob);
        }
        
        private ResType helper(TreeNode root) {
            if (root == null) {
                return new ResType();
            }
            ResType cur = new ResType();
            ResType left = helper(root.left);
            ResType right = helper(root.right);
            cur.rob = left.notRob + right.notRob + root.val;
            cur.notRob = Math.max(left.rob, left.notRob) + Math.max(right.rob, right.notRob);
            return cur;
        }
    }
    
    class ResType {
        int rob;
        int notRob;
    }
  • 相关阅读:
    linux 安装Python3
    MYSQL 字符集设置(终端的字符集)
    Linux LVM Logical Volume Management 逻辑卷的管理
    oracle 重命名和重定位数据文件(Oracle Renaming and Relocating Datafiles)
    Azkaban编译
    基于hive的transform实现自定义分隔符数据导出
    MapReduce优化设置
    hive.groupby.skewindata环境变量与负载均衡
    hive的基本操作
    Shell 数组的定义和使用
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12549132.html
Copyright © 2011-2022 走看看