[LeetCode] 337. 打家劫舍 III (树形dp)

题目

在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。

计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  • 满足“如果题目求解目标是s规则,则求解流程可以定为以每一节点为根节点的子树在s规则下的每个答案,并且最终答案一定在其中。”的特点,使用树形dp。
  • 求以当前节点为根节点的最高金额,即return max(当前节点金额+当前节点的左子树(存在的话)的左右子节点的最大金额+当前节点的右子树(存在的话)的左右子节点的最大金额,偷当前节点的左右子树的最大金额)
  • 最终返回maxProfit(root)即是所求。

代码

/**
 * 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) {
        return maxProfit(root);
    }
    
    private int maxProfit(TreeNode root) {
		if (root == null) {
			return 0;
		}

		// 方案一 偷取当前节点
		int profit1 = root.val;
		if (root.left != null) {
			profit1 += maxProfit(root.left.left) + maxProfit(root.left.right);
		}
		if (root.right != null) {
			profit1 += maxProfit(root.right.left) + maxProfit(root.right.right);
		}

		// 方案二 不偷取当前节点
		int profit2 = 0;
		profit2 += maxProfit(root.left) + maxProfit(root.right);

		return Math.max(profit1, profit2);
	}
}

posted on 2019-10-24 22:27  coding_gaga  阅读(386)  评论(0编辑  收藏  举报

导航