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;
    }
  • 相关阅读:
    漫步温泉大道有感
    不可多得的”魔戒“:一堂成功学大师们的浓缩课
    四川新闻网关于IT诗人的报道
    赠徐蕴筝(帮别人名字作诗)
    再游草堂
    赠申芳菲(帮别人名字作诗)
    Oracle内部错误:ORA00600[15801], [1]一例
    Oracle内部错误:ORA00600[OSDEP_INTERNAL]一例
    Oracle O立方服务平台(O3SP)
    Oracle RAC内部错误:ORA00600[keltnfyldmInit]一例
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12549132.html
Copyright © 2011-2022 走看看