Leetcode 337. House Robber III
来源:互联网 发布:mysql 更改character 编辑:程序博客网 时间:2024/05/21 17:38
Naive solution. There are many overlapping sub problems.
e.g. if we rob(root), we need to know rob(left), rob(right), rob(left.left), rob(left.right), ...
then, say if we want to rob(root.left), the algorithm below calculates rob(left.left), rob(left.right) again.
/** * There are two choices, rob root house or skip the root house. * Take the maximum of the two choices. * If we choose to rob the root, then we cannot rob the left and right child of the root. * robRoot = root.val + root.left.left + root.left.right + root.right.left + root.right.right * If we choose not to rob the root, * robNoRoot = root.left + root.right * Then take the maximum as profit, * money = max(robRoot, robNoRoot) */ public class Solution { public int rob(TreeNode root) { if (root == null) return 0; int robRoot = root.val; // rob the root house if (root.left != null) { robRoot += rob(root.left.left) + rob(root.left.right); } if (root.right != null) { robRoot += rob(root.right.left) + rob(root.right.right); } return Math.max(robRoot, rob(root.left)+rob(root.right)); }}Using a hashmap to save the result for every root so that we can avoid duplicate calculating.
public class Solution { public int rob(TreeNode root) { return helper(root, new HashMap<>()); } public static int helper(TreeNode r, HashMap<TreeNode, Integer> map) { if (r == null) return 0; if (map.containsKey(r)) return map.get(r); int robRoot = r.val; // rob the root house if (r.left != null) robRoot += helper(r.left.left, map) + helper(r.left.right, map); if (r.right != null) robRoot += helper(r.right.left, map) + helper(r.right.right, map); int money = Math.max(robRoot, helper(r.left, map) + helper(r.right, map)); map.put(r, money); return money; }}
0 0
- [leetcode] 337. House Robber III
- LeetCode#337. House Robber III
- LeetCode *** 337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337.House Robber III
- LeetCode 337. House Robber III
- Leetcode 337. House Robber III
- leetcode 337. House Robber III
- LeetCode - 337. House Robber III
- 【LeetCode】337. House Robber III
- 【leetcode】337. House Robber III
- [leetcode] 337. House Robber III
- LeetCode 337. House Robber III
- 【LeetCode】337. House Robber III
- LeetCode 337. House Robber III
- LeetCode 337. House Robber III
- 28.java多线程实现文件的下载
- Faded 英文说唱版
- 简略git push步骤
- 安卓手机的后门控制工具SPADE
- Linux进程隐藏的一种实现思路
- Leetcode 337. House Robber III
- 乌克兰又断电了,看Ukrenergo断电事件的技术分析与防护方案
- 利用Cobalt strike一步步教你发送钓鱼邮件
- reading session
- Tomcat(三) Tomcat安装配置:Tomcat+Nginx+keepalived 实现动静分离、Session会话保持的高可用集群
- 【LeetCode】 116. Populating Next Right Pointers in Each Node
- react+redux框架配置从无到有直到正常运行全流程(上)
- 使用spring全注解实现继承时遇到的问题
- Aircrack-ng 之wifi破解