在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:输入: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
解题思路1:递归法,问题可以拆成两个子问题,第一个是从根节点开始遍历,然后遍历其子树的子树,找出最大的节点值之和;第二种情况是从根节点的两棵子树开始遍历,然后间隔遍历其子树的子树。
class Solution {
public int rob(TreeNode root) {
if(root == null){
return 0;
}
int sum1 = root.val;
if(root.left != null){
sum1+= rob(root.left.left)+rob(root.left.right);
}
if(root.right != null){
sum1+=rob(root.right.left)+rob(root.right.right);
}
int sum2 = rob(root.left)+rob(root.right);
return Math.max(sum1,sum2);
}
}
解题思路2: 由于上一种解决方法中我们发现有重复计算的子问题,由于爷爷节点计算时,我们计算了两个子节点和四个孙子节点,当儿子节点当爷爷节点时,就会发现需要重复计算一次上一个爷爷节点的孙子节点。所以我们采用map来当作缓存,如果缓存中有数据就从缓存中拿取。
class Solution {
public int rob(TreeNode root) {
Map<TreeNode,Integer> cache = new HashMap<TreeNode,Integer>();
return subRob(root,cache);
}
private int subRob(TreeNode root, Map<TreeNode,Integer> cache){
if(root == null){
return 0;
}
if(cache.containsKey(root)){
return cache.get(root);
}
int sum1 = root.val;
if(root.left != null){
sum1+= subRob(root.left.left,cache)+subRob(root.left.right,cache);
}
if(root.right != null){
sum1+=subRob(root.right.left,cache)+subRob(root.right.right,cache);
}
int sum2 = subRob(root.left,cache)+subRob(root.right,cache);
int result = Math.max(sum1,sum2);
cache.put(root,result);
return result;
}
}
解题思路3:采用动态规划的问题。对于当前节点来说,只有两种状态,偷与不偷,当root节点状态为偷时,它的结果就是两棵子树不偷状态的结果和加上root;当root节点状态是不偷时,它的结果就是两个子节点能偷的和。用一个数组state来记录状态,state[0]为不偷,state[1]为偷。
class Solution {
public int rob(TreeNode root) {
int[] state = subRob(root);
return Math.max(state[0],state[1]);
}
private int[] subRob(TreeNode root){
if(root == null) return new int[2];
int[] state = new int[2];
int[] leftState = subRob(root.left);
int[] rightState = subRob(root.right);
state[0] = Math.max(leftState[0],leftState[1])+Math.max(rightState[0],rightState[1]);
state[1] = root.val+leftState[0]+rightState[0];
return state;
}
}