Description
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:
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
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.
Solution
Recursion with note, time O(n), space O(n)
robRecur(root)的返回值是rob root和not rob root的max。需要用一个HashMap去辅助记录以避免重复递归。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
return robRecur(root, new HashMap<>());
}
public int robRecur(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 += robRecur(root.left.left, map) + robRecur(root.left.right, map);
}
if (root.right != null) {
val += robRecur(root.right.left, map) + robRecur(root.right.right, map);
}
int max = Math.max(root.val + val // rob root
, robRecur(root.left, map) + robRecur(root.right, map)); // no rob root
map.put(root, max);
return max;
}
}
Recursion, time O(n), space O(n)
返回一个int[]以区分rob与否,这样就将一个问题拆分成了不重叠的两个子问题,不会造成重复的递归计算。
返回一个array是java里面好用的方式啊。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
int[] res = robRecur(root);
return Math.max(res[0], res[1]);
}
public int[] robRecur(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] left = robRecur(root.left);
int[] right = robRecur(root.right);
int[] res = new int[2];
// no rob root
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// rob root
res[1] = root.val + left[0] + right[0];
return res;
}
}