337. House Robber III

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了337. House Robber III相关的知识,希望对你有一定的参考价值。

和前两题已经关系不大了……是树的dfs,加上一个表track back

 1     public int rob(TreeNode root) {
 2         if(root == null) {
 3             return 0;
 4         }
 5         Map<TreeNode, Integer> a = new HashMap<TreeNode, Integer>();
 6         Map<TreeNode, Integer> b = new HashMap<TreeNode, Integer>();
 7         return Math.max(sum(root, true, a, b), sum(root, false, a, b));
 8     }
 9     
10     private int sum(TreeNode root, boolean visited, Map<TreeNode, Integer> a, Map<TreeNode, Integer> b) {
11         if(root == null) {
12             return 0;
13         }
14         if (!visited && a.containsKey(root)) {
15             return a.get(root);
16         }
17         if (visited && b.containsKey(root)) {
18             return b.get(root);
19         }
20         int left = sum(root.left, false, a, b);
21         int right = sum(root.right, false, a, b);
22         if(visited) {
23             b.put(root, left + right);
24             return left + right;
25         } else {
26             int leftTrue = sum(root.left, true, a, b);
27             int rightTrue = sum(root.right, true, a, b);
28             int sum = Math.max(left + right, leftTrue + rightTrue + root.val);
29             a.put(root, sum);
30             return sum;
31         }
32     }

 

以上是关于337. House Robber III的主要内容,如果未能解决你的问题,请参考以下文章

337. House Robber III

337. House Robber III

337. House Robber III

337. House Robber III

337. House Robber III

[leetcode-337-House Robber III]