337. House Robber III

2018-04-23  本文已影响0人  SummerDreamEve

题目

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.

思路

Find the subproblem of this problem. There is two situations:

  1. the root is not robbed
  2. the root is robbed
    If we want to include both this two situations information we can use an array with length 2.
int[] res = new int[2];

代码

class Solution {
    public int rob(TreeNode root) {
        int[] res = robSub(root);
       return Math.max(res[0],res[1]);
    }
     public int[] robSub(TreeNode root){
         if(root == null) return new int[2]; 
         int[] left = robSub(root.left);
         int[] right = robSub(root.right);
         
         int[] sum = new int[2];
         
         sum[0] = Math.max(left[0],left[1])+Math.max(right[0],right[1]);//not rob
         sum[1] = root.val+left[0]+right[0];//rob
         
         return sum;         
     }         
}

参考链接

https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem

上一篇下一篇

猜你喜欢

热点阅读