题目:
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.
解答:
1.最原始的想法是对每个点分两种情况考虑:如果取这个点,那么下一次取的就是它的孙结点;如果不取这个点,那么下一次取的就是它的子结点:
代码:
private Map<TreeNode, Integer> map = new HashMap<>();
public int rob(TreeNode root) {
if (root == null) return 0;
if (map.containsKey(root)) return map.get(root);
int result = 0;
if (root.left != null) {
result += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
result += rob(root.right.left) + rob(root.right.right);
}
result = Math.max(root.val + result, rob(root.left) + rob(root.right));
map.put(root, result);
return result;
}
这里用map来记下当前结点的和,避免一些重复记算。
2.Greedy算法
public int[] Helper(TreeNode root) {
if (root == null) return new int[2];
//记录下取和不取两种情况的最大值
int[] left = Helper(root.left);
int[] right = Helper(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;
}
public int rob(TreeNode root) {
int[] res = Helper(root);
return Math.max(res[0], res[1]);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。