您的位置:首页 > 编程语言 > Java开发

LeetCode-337. House Robber III(JAVA)(树形结构)

2017-04-16 17:54 183 查看

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.

题意:不能连续抢直接相连的两个节点。即例2中,抢了3就不能抢4,5。问最多能抢多少。

给一个二叉树,求它不直接相连的节点的val和最大为多少。

如果抢了当前节点,那么它的左右孩子就肯定不能抢了。

如果没有抢当前节点,左右孩子抢不抢取决于左右孩子的孩子的val大小。

上两道题目:

LeetCode-198. House Robber (JAVA)

LeetCode-213. House Robber II (JAVA)


第一种方法

动态规划法??(or Greedy算法??)

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];
// 下标1 存储选择该结点
// 下标0 存储不选择该结点
// 不选择当前结点
res[0] = Math.max(left[0], left[1]) +
Math.max(right[0], right[1]);
// 选择当前结点
res[1] = root.val + left[0] + right[0];
return res;
}


第二种方法

对每个点分两种情况考虑:如果取这个点,那么下一次取的就是它的孙结点;如果不取这个点,那么下一次取的就是它的子结点:这里用map来记下当前结点的和,避免一些重复记算(没有也能AC)[b]。[/b]

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;
}参考:
LeetCode-198. House Robber (JAVA)寻找数组不相邻组合最大值DP

LeetCode-213. House Robber II (JAVA)(有环)

https://segmentfault.com/a/1190000005895670
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息