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:
- the root is not robbed
- 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];
- When the root is not robbed: res[0] = max(root.left)+max(root.right) (把问题扔给左右子树)
- When the root is robbed: res[0] =root.val+left[0]+right[0]
代码
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