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 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 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.

Solution:[DP思想] 递归 Post-order 分治 Bottom-up向上传递

思路:
DP思路和 198. House Robber 思路一样
实现:分治左右树,分别得到左/右子树 的 含cur_max/不含prev_max 相邻结点的 最大值,在当前结点Conquer计算出新的含本结点cur_max(上一层不能有相邻的,只能用left/right.prev)和prev_max(没相邻orNot限制,选前面最大的就行)
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    class Result {  
        int cur_max;
        int prev_max;
        Result(int cur_max, int prev_max) {
            this.cur_max = cur_max;
            this.prev_max = prev_max;
        }
    }
    
    public int rob(TreeNode root) {
        Result result = dfsHelper(root);
        return Math.max(result.cur_max, result.prev_max);
    }
    
    private Result dfsHelper(TreeNode node) {
        if(node == null) return new Result(0, 0);
        Result left = dfsHelper(node.left);
        Result right = dfsHelper(node.right);
    
        // consider this one
        int cur_max = left.prev_max + right.prev_max + node.val; 
        // if including negative case
        // int cur_max = Math.max(left.prev_max + right.prev_max, Math.max(left.prev_max, right.prev_max)) + node.val;  
                       
        // don't consider this one
        int prev_max = Math.max(left.cur_max, left.prev_max) + Math.max(right.cur_max, right.prev_max); 
        
        Result result = new Result(cur_max, prev_max);
        return result;
    }
}

你可能感兴趣的:(337. House Robber III)