题目描述
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.
题目链接
https://leetcode.com/problems/house-robber-iii/
方法思路
Step1: simple recursion
class Solution {
//初步的递归版本
//Runtime: 676 ms, faster than 19.66%
//Memory Usage: 39.3 MB, less than 49.82%
public int rob(TreeNode root){
if(root == null) return 0;
int include = 0, exclude = 0;
if(root.left != null){
include += rob(root.left.left) + rob(root.left.right);
}
if(root.right != null){
include += rob(root.right.left) + rob(root.right.right);
}
exclude += rob(root.left) + rob(root.right);
return Math.max(include + root.val, exclude);
}
}
Step2: simple recursion + memo(HashMap)
class Solution {
//Runtime: 4 ms, faster than 54.51%
//Memory Usage: 42.8 MB, less than 6.91%
public int rob(TreeNode root) {
return robSub(root, new HashMap<>());
}
private int robSub(TreeNode root, Map<TreeNode, Integer> map) {
if (root == null) return 0;
if (map.containsKey(root)) return map.get(root);
int val = 0;
if (root.left != null) {
val += robSub(root.left.left, map) + robSub(root.left.right, map);
}
if (root.right != null) {
val += robSub(root.right.left, map) + robSub(root.right.right, map);
}
val = Math.max(val + root.val, robSub(root.left, map) + robSub(root.right, map));
map.put(root, val);
return val;
}
}
Step3: simple recursion
dfs all the nodes of the tree, each node return two number, int[] num, num[0] is the max value while rob this node, num[1] is max value while not rob this value. Current node return value only depend on its children’s value. Transform function should be very easy to understand.
public class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 38.6 MB, less than 61.82%
public int rob(TreeNode root) {
int[] num = dfs(root);
return Math.max(num[0], num[1]);
}
private int[] dfs(TreeNode x) {
if (x == null) return new int[2];
int[] left = dfs(x.left);
int[] right = dfs(x.right);
int[] res = new int[2];
res[0] = left[1] + right[1] + x.val;
res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return res;
}
}