(Java) LeetCode 337. House Robber III —— 打家劫舍 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.


劫匪真是太专业了,连二叉树都懂…本题是LeetCode 198. House Robber —— 打家劫舍LeetCode 213. House Robber II —— 打家劫舍 II的联合升级版,但其实并没有算法上的联系。思路上倒是有相同的地方。

先分析一下思路。首先遇到一个根房子,我们有两种选择:偷它或者不偷它。如果选择偷,那么首先它里面的钱要先放入钱包,之后它的两片叶子一定不可以偷。如果选择不偷,那么要继续“拜访”叶子房子。之所以是拜访,是因为就算不偷根房子,也不是一定要偷叶子房子,可偷可不偷。

分析完成之后就看如何实现。遇到树第一个想到的就是递归,实现起来也确实是很简单。详见解法一代码注释。

提交解法一,发现有的时候超时,有的时候不超时,迷之测试啊简直是。不过既然不稳定,那就想想有没有别的办法。递归之所以太慢了是因为每次递归到一个节点都必须要递归到树的最外层才知道这一个节点的结果。如果在递归的过程中把结果存起来就会大大的提高运行速度,这时候就有点像198和213动态规划的思路了。假设每一个节点都有两种结果,分别存储在dp[0]和dp[1]中,分别代表不偷这个节点房子和偷这个节点房子。那么将从它的左右叶子开始偷的结果分别存储在dpLeft以及dpRight两个数组中,其中dpLeft[0]和dpRight[0]代表没有偷左右叶子,dpLeft[1]和dpRight[1]代表偷了左右叶子。那么对于dp[0](没偷根节点)来说,就是取偷或者不偷叶子节点的最大值,即dp[0]  = max(dpLeft[0], dpLeft[1]) + max(dpRight[0], dpRight[1])。这里要时刻记着不偷根节点不代表一定要偷叶子。偷不偷叶子都可能产生最大值,所以是取max加和。之后dp[1]就是偷了根节点的房子,那么就一定不可以偷叶子节点,所以dp[1] = root.val + dpLeft[0] + dpRight[0]。思路依然清晰,只要弄清楚各个数组元素代表的意义即可。见下代码。


解法一(Java)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;
        return Math.max(robOK(root), robNG(root)); 
    }
    
    private int robOK(TreeNode root) {
        if (root == null) return 0;
        return root.val + robNG(root.left) + robNG(root.right);
    }
    
    private int robNG(TreeNode root) {
        if (root == null) return 0;
        return rob(root.left) + rob(root.right);
    }
}

解法二(Java)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;
        return Math.max(get(root)[0], get(root)[1]);
    }
    
    private int[] get(TreeNode root) {
        int[] dp = {0, 0};
        if (root == null) return dp;
        int[] dpLeft = get(root.left);
        int[] dpRight = get(root.right);
        dp[0] = Math.max(dpLeft[0], dpLeft[1]) + Math.max(dpRight[0], dpRight[1]);
        dp[1] = root.val + dpLeft[0] + dpRight[0];
        return dp;
    }
}
原文地址:https://www.cnblogs.com/tengdai/p/9282546.html