zoukankan      html  css  js  c++  java
  • 337. House Robber III java solutions

    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.

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     
     
     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 int rob(TreeNode root) {
    12         int[] res = Robdfs(root);
    13         return Math.max(res[0],res[1]);
    14     }
    15     
    16     public int[] Robdfs(TreeNode root){
    17         if(root == null) return new int[2];
    18         int[] left = Robdfs(root.left);
    19         int[] right = Robdfs(root.right);
    20         int[] ans = new int[2];
    21         ans[0] = left[1] + root.val + right[1];
    22         ans[1] = Math.max(left[0], left[1]) + Math.max(right[0],right[1]);
    23         return ans;
    24     }
    25 }

    DFS中,root为null时,返回长度为2的空数组;
    建立结果数组res时,res[0]是包括根节点的情况,res[1]是不包含根节点的情况。而非按左右子树来进行划分的。

  • 相关阅读:
    Nginx-limit_req限速配置示例
    Linux-配置虚拟IP实例
    jQuery中获取a标签的值
    js时间格式化
    a标签与js的冲突
    spring MVC页面的重定向
    EL表达式遍历集合获取下标
    商城项目之实战-购物车模块
    js中得计算问题算式结果拼接成字符串怎么解决
    js中数值类型相加变成拼接字符串的问题
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5452979.html
Copyright © 2011-2022 走看看