LeetCode OJ 337. House Robber III
Posted Black_Knight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于LeetCode OJ 337. House Robber III的主要内容,如果未能解决你的问题,请参考以下文章
<LeetCode OJ> 337. House Robber III
[leetcode-337-House Robber III]
[leetcode] 337.House Robber III
leetcode No337. House Robber III