0337. House Robber III (M)

House Robber III (M)

题目

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:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

题意

给定一个二叉树,从中选取互不直接相连的若干数,使其和最大。

思路

直接暴力递归也能过,为了优化加上记忆化。


代码实现

Java

class Solution {
    public int rob(TreeNode root) {
        Map<TreeNode, Integer> memTo = new HashMap<>();
        Map<TreeNode, Integer> memNot = new HashMap<>();
        return Math.max(rob(root, true, memTo, memNot), rob(root, false, memTo, memNot));
    }

    private int rob(TreeNode root, boolean canRob, Map<TreeNode, Integer> memTo, Map<TreeNode, Integer> memNot) {
        if (root == null) {
            return 0;
        }

        if (canRob && memTo.containsKey(root)) {
            return memTo.get(root);
        }

        if (!canRob && memNot.containsKey(root)) {
            return memNot.get(root);
        }

        int toRob = canRob ? root.val + rob(root.left, false, memTo, memNot) + rob(root.right, false, memTo, memNot) : 0;
        int notRob = rob(root.left, true, memTo, memNot) + rob(root.right, true, memTo, memNot);
        int tmp = Math.max(toRob, notRob);

        if (canRob) {
            memTo.put(root, tmp);
        } else {
            memNot.put(root, tmp);
        }

        return tmp;
    }
}
posted @ 2020-11-23 16:59  墨云黑  阅读(109)  评论(0编辑  收藏  举报