337-House Robber III

kevin聰發表於2018-05-06

Description

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.


問題描述

小偷發現來偷東西的新地點。這塊區域只有一個入口, 被稱作”root”.除了root之外, 每個房間有且僅有一個父房間。轉了一圈之後, 小猴意識到這塊區域的所有房間形成了一個二叉樹。如果兩個直接連線的房間在同一晚被偷, 那麼警報會被觸發。

在不會觸發警報的情況下, 找出小偷當天可以獲得的最大的金額。


問題分析

強烈建議看一下這個連結
https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem


解法1

class Solution {
    public int rob(TreeNode root) {
        if (root == null) return 0;

        int val = 0;
        if (root.left != null)  val += rob(root.left.left) + rob(root.left.right);
        if (root.right != null) val += rob(root.right.left) + rob(root.right.right);
        //兩種情況, 當前節點偷與不偷
        return Math.max(val + root.val, rob(root.left) + rob(root.right));
    }
}

解法2

/*
與解法1的不同之處在於使用map儲存了中間狀態
*/
class Solution {
    public int rob(TreeNode root) {
        return robSub(root, new HashMap());
    }

    private int robSub(TreeNode root, Map<TreeNode, Integer> map) {
        if (root == null) return 0;
        if (map.containsKey(root)) return map.get(root);

        int val = 0;
        if (root.left != null)  val += robSub(root.left.left, map) + robSub(root.left.right, map);
        if (root.right != null) val += robSub(root.right.left, map) + robSub(root.right.right, map);
        val = Math.max(val + root.val, robSub(root.left, map) + robSub(root.right, map));
        map.put(root, val);

        return val;
    }
}

解法3

/*
當前節點存在偷與不偷兩種情況, 於是可以使用一個只有兩個元素的陣列來儲存每個節點的狀態
res[0]為不偷, res[1]為偷
*/
class Solution {
    public int rob(TreeNode root) {
        int[] res = robSub(root);
        return Math.max(res[0], res[1]);
    }

    private int[] robSub(TreeNode root) {
        if (root == null) return new int[2];

        int[] left = robSub(root.left);
        int[] right = robSub(root.right);
        int[] res = new int[2];
        res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        res[1] = root.val + left[0] + right[0];

        return res;
    }
}

相關文章