zoukankan      html  css  js  c++  java
  • LeetCode OJ 337. 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.

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

    对于这个题目我们有什么思路呢?我们从根节点开始有两种选择,要么偷取根节点的值,要么不偷取根节点。偷取根节点的话,我们接下来只能偷取根节点孩子节点的孩子节点。如果不偷取根节点的话,我们可以直接偷取根节点的孩子节点。然后我们把这两种方式得到的值进行比较,取较大的那个。因此这是一个递归的过程:

    rob(root) = max{rob(root.left) + rob(root.rght), root.val + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right)}

    if(root == null) rob(root) = 0;

    if(root.left == null && root.right == null) rob(root) = root.val

    有了上面的递归表达式,我们就很容易进行编程啦!代码如下:

     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         if(root == null) return 0;
    13         if(root.left == null && root.right == null) return root.val;
    14         int maxnum1 = 0;
    15         int maxnum2 = 0;
    16         maxnum1 = rob(root.left) + rob(root.right);
    17         if(root.left != null || root.right != null){
    18             int num1 = root.left!=null?rob(root.left.left) + rob(root.left.right):0;
    19             int num2 = root.right!=null?rob(root.right.left) + rob(root.right.right):0;
    20             maxnum2 = num1 + num2 + root.val;
    21         }
    22         return maxnum1>maxnum2?maxnum1:maxnum2;
    23     }
    24 }
  • 相关阅读:
    【分享】管理的最高境界是简单
    建立市场化风险评估机制推进地方政府信用评级建设
    手游-神雕侠侣 85侠客纪攻略(已通关)
    使用git的分支功能实现定制功能摘取与组合的想法
    组内正则培训记录
    组内Linq培训记录
    一次代码重构记录
    git代码库误操作还原记录
    关于代码重构的开始
    如何管理高手、大牛?
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5508165.html
Copyright © 2011-2022 走看看