• LeetCode-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 1:

         3
        / 
       2   3
            
         3   1
    

    Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

    Example 2:

         3
        / 
       4   5
      /     
     1   3   1
    

    Maximum amount of money the thief can rob = 4 + 5 = 9.

    Analysis:

    Two states at each root: rob root, not rob root.

    Solution:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public class RobResult {
    12         int robProfit;
    13         int noRobProfit;
    14         public RobResult(int rp, int nrp){
    15             robProfit = rp;
    16             noRobProfit = nrp;
    17         }
    18     }
    19     
    20     public int rob(TreeNode root) {
    21         RobResult res = robRecur(root);
    22         return Math.max(res.robProfit,res.noRobProfit);        
    23     }
    24 
    25     public RobResult robRecur(TreeNode cur){
    26         if (cur==null){
    27             return new RobResult(0,0);
    28         }
    29 
    30         RobResult leftRes = robRecur(cur.left);
    31         RobResult rightRes = robRecur(cur.right);
    32 
    33         RobResult curRes = new RobResult(leftRes.noRobProfit+rightRes.noRobProfit+cur.val, Math.max(leftRes.noRobProfit,leftRes.robProfit)+Math.max(rightRes.noRobProfit,rightRes.robProfit));
    34         return curRes;
    35     }
    36 }
  • 相关阅读:
    HDU5730 Shell Necklace
    BZOJ4883 [Lydsy2017年5月月赛]棋盘上的守卫
    Spring boot 配置文件
    org.joda.time.DateTime 日期操作
    Elasticsearch + Springboot 启动报错 java.net.ConnectException: Connection refused
    centos7 在docker下安装es Elasticsearch
    centos 7 。 docker 安装rabbitmq 以及集权搭建
    linux 安装mysql5.7.25
    安装rabbtimq CentOS 7
    docker + spring boot 打包 部署。
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5728873.html
Copyright © 2020-2023  润新知