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 realizedthat "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
相关文章推荐
- 数据库中的树形结构 - JAVA 设计 (通用)
- java实现文件夹的遍历(树形结构)
- JavaSwing实现树形结构
- 对于java的树形结构的抽象与拓展---完善
- java 递归遍历树形结构
- 数据库中的树形结构 - JAVA 设计 (通用)
- 递归算法结合数据库解析成java树形结构
- 黑马程序员//JAVA 树形结构程序事…
- JAVA 树形结构程序事件实例
- java对树形结构深度优先的访问
- JAVA树形结构
- 树形结构java代码以及结果
- Java 树形结构
- java、js中实现无限层级的树形结构(类似递归)
- java 递归查询树形结构
- java树形结构 两种算法
- 使用递归算法结合数据库解析成java树形结构
- Java基础之IO流,使用File类以树形结构打印指定文件目录
- java学习笔记 使用递归 将文件目录树形结构输出,递归删除目录 文件夹。
- java 树形结构