• 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 }
  • 相关阅读:
    UIAutomator环境搭建
    Appium环境搭建
    Java单元测试 Junit TestNG之介绍
    IDEA操作jdbc总结
    tomcat启动失败的解决办法
    Java 图书管理项目
    某某服-EDR终端任意用户登录 0day
    深X服 EDR终端检测系统RCE漏洞复现
    通达OA任意文件上传+文件包含RCE漏洞复现(附自写EXP)
    Joomla-3.4.6远程代码执行漏洞复现
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5728873.html
Copyright © 2020-2023  润新知