• 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 }
  • 相关阅读:
    ubuntu 安装QT 5.0出现错误:Failed to load platform plugin "xcb".
    Ubuntu手动编译GCC
    C++面试题集锦(一)
    C++排序系列(一) 插入排序之折半插入排序
    关于内存对齐的面试题
    C++中的static_cast, dynamic_cast和reinterpret_cast
    C++排序系列(二) 交换排序之简单排序
    Cannot open include file: 'iphlpapi.h': No such file or directory(最终解决方法)
    C++排序系列(一) 插入排序之直接插入排序
    ubuntu aptget update时出现W: GPG 错误
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5508165.html
Copyright © 2020-2023  润新知