1. 程式人生 > >House Robber III

House Robber III

math span != clas cal ace def rmi tin

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
  3
 / 2   3
 \   \ 
  3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

    3
   /   4   5
 / \   \ 
1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

這題一開始用遞歸 結果超時;隨機加cache變成DP。。通過了

helper1表示搶root

helper2表示不搶root;此處註意不搶root時 即可以搶root.left和root.right 也可以不搶它們 二取其一 所以註意42-47行

 

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int x) { val = x; }
 7  * }
 8  */
 9 public class
Solution { 10 /** 11 * @param root: The root of binary tree. 12 * @return: The maximum amount of money you can rob tonight 13 */ 14 Map<TreeNode, Integer> map1 = new HashMap<TreeNode, Integer>(); 15 Map<TreeNode, Integer> map2 = new HashMap<TreeNode, Integer>(); 16 public int houseRobber3(TreeNode root) { 17 // write your code here 18 if(root==null) return 0; 19 return Math.max(helper1(root), helper2(root)); 20 } 21 // include root 22 private int helper1(TreeNode root){ 23 if(map1.containsKey(root)){ 24 return map1.get(root); 25 } 26 int sum = root.val; 27 if(root.left!=null){ 28 sum += helper2(root.left); 29 } 30 if(root.right!=null){ 31 sum += helper2(root.right); 32 } 33 map1.put(root, sum); 34 return sum; 35 } 36 // not include root 37 private int helper2(TreeNode root){ 38 if(map2.containsKey(root)){ 39 return map2.get(root); 40 } 41 int sum = 0; 42 if(root.left!=null){ 43 sum += Math.max(helper1(root.left), helper2(root.left)); 44 } 45 if(root.right!=null){ 46 sum += Math.max(helper1(root.right), helper2(root.right)); 47 } 48 map2.put(root, sum); 49 return sum; 50 } 51 }

House Robber III