House Robber III


Question

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.

Solution

經典 DP 問題加上 Tree 的組合技,自己第一次寫有想出來,用 recursion,但因為會有重複計算的問題,所以效率比較差。解答用 DP 效率好一些

public int rob(TreeNode root) {
        return robSub(root, new HashMap<>());
    }

    private int robSub(TreeNode t, Map<TreeNode, Integer> map) {
        if (t == null) {
            return 0;
        }

        if (map.containsKey(t)) {
            return map.get(t);
        }

        int val = 0;

        if (t.left != null) {
            val += robSub(t.left.left, map) + robSub(t.left.right, map);
        }

        if (t.right != null) {
            val += robSub(t.right.left, map) + robSub(t.right.right, map);
        }

        val = Math.max(t.val + val, robSub(t.left, map) + robSub(t.right, map));

        map.put(t, val);

        return val;
    }

results matching ""

    No results matching ""