337. House Robber III

Posted 咖啡中不塌缩的方糖

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了337. House Robber III相关的知识,希望对你有一定的参考价值。

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.

 

这道题本质上是与之前的两道题一样的。 但是区别在于这道题是Btree。 首先最好想的是NoRob与Rob两个method,分别计算。具体code如下

 public int Rob(TreeNode root) {
        return Math.Max(Robb(root), NoRob(root));
    }
    
    public int Robb(TreeNode root)
    {
        if(root == null) return 0;
        var left = NoRob(root.left);
        var right = NoRob(root.right);
        return left+right+root.val;
    }
    
     public int NoRob(TreeNode root)
    {
        if(root == null) return 0;
        return Math.Max(Robb(root.left), NoRob(root.left))+Math.Max(Robb(root.right), NoRob(root.right));
    }

 

这个submit的时候超时了。问题在于里面Robb与NoRob两个method实际上repeat了很多次。需要改进算法,一种解决方法是输出是array。第一个数存的是恰好rob这个Node的,第二数存的是没有Rob这个node的最大值。最后只要比较root输出的这连个值,取最大值就好了。

具体代码为

public int Rob(TreeNode root) {
        var res = Robb(root);
        return Math.Max(res[0],res[1]);
    }
    
    public int[] Robb(TreeNode root)
    {
        var res = new int[2];
        res[0] = 0;
        res[1] = 0;
        if(root == null) return res;
        var left = Robb(root.left);
        var right = Robb(root.right);
        res[0] = root.val+left[1]+right[1];
        res[1] = Math.Max(left[0],left[1]) + Math.Max(right[0],right[1]);
        return res;
    }

 

此时想想能不能用第一种方法实现呢。理论上是可行的,即输入的时候加一个Hashtable,用来存每一个Node的极值。

以上是关于337. House Robber III的主要内容,如果未能解决你的问题,请参考以下文章

337. House Robber III

337. House Robber III

337. House Robber III

337. House Robber III

337. House Robber III

[leetcode-337-House Robber III]