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:
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.
问题描述
小偷发现来偷东西的新地点。这块区域只有一个入口, 被称作”root”.除了root之外, 每个房间有且仅有一个父房间。转了一圈之后, 小猴意识到这块区域的所有房间形成了一个二叉树。如果两个直接连接的房间在同一晚被偷, 那么警报会被触发。
在不会触发警报的情况下, 找出小偷当天可以获得的最大的金额。
问题分析
解法1
class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
int val = 0;
if (root.left != null) val += rob(root.left.left) + rob(root.left.right);
if (root.right != null) val += rob(root.right.left) + rob(root.right.right);
//两种情况, 当前节点偷与不偷
return Math.max(val + root.val, rob(root.left) + rob(root.right));
}
}
解法2
/*
与解法1的不同之处在于使用map保存了中间状态
*/
class Solution {
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;
}
}
解法3
/*
当前节点存在偷与不偷两种情况, 于是可以使用一个只有两个元素的数组来保存每个节点的状态
res[0]为不偷, res[1]为偷
*/
class Solution {
public int rob(TreeNode root) {
int[] res = robSub(root);
return Math.max(res[0], res[1]);
}
private int[] robSub(TreeNode root) {
if (root == null) return new int[2];
int[] left = robSub(root.left);
int[] right = robSub(root.right);
int[] res = new int[2];
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = root.val + left[0] + right[0];
return res;
}
}