码迷,mamicode.com
首页 > 其他好文 > 详细

337. House Robber III

时间:2016-06-29 13:22:23      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

和前两题已经关系不大了……是树的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

标签:

原文地址:http://www.cnblogs.com/warmland/p/5626426.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!