博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode OJ 337. House Robber III
阅读量:4552 次
发布时间:2019-06-08

本文共 2072 字,大约阅读时间需要 6 分钟。

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  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 }

 

转载于:https://www.cnblogs.com/liujinhong/p/5508165.html

你可能感兴趣的文章
ES6阅读笔记
查看>>
数字基带信号分类
查看>>
移动HTML5前端性能优化指南(转)
查看>>
Jq 遍历each()方法
查看>>
Android源码分析:Telephony部分–phone进程
查看>>
关于 redis.properties配置文件及rule
查看>>
WebService
查看>>
关于Java中重载的若干问题
查看>>
Java中start和run方法的区别
查看>>
23种设计模式中的命令模式
查看>>
[转载]年薪10w和年薪100w的人,差在哪里?
查看>>
shell 日期参数
查看>>
package的使用
查看>>
括号生成
查看>>
优秀的前端需要做到什么?
查看>>
aws cli command line interface的安装与使用
查看>>
10)将地址换成常量
查看>>
箭头函数
查看>>
android MVC && MVP && MVVM分析和对照
查看>>
jsp知识点
查看>>