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.java

Determine the maximum amount of money the thief can rob tonight without alerting the police.ide

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:this

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.

題意

給定一個二叉樹,從中選取互不直接相連的若干數,使其和最大。code

思路

直接暴力遞歸也能過,爲了優化加上記憶化。orm


代碼實現

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;
    }
}
相關文章
相關標籤/搜索