前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode337. House Robber III

leetcode337. House Robber III

作者头像
眯眯眼的猫头鹰
发布2018-10-31 11:06:54
3600
发布2018-10-31 11:06:54
举报

题目要求

代码语言:javascript
复制
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.

即如何从树中选择几个节点,在确保这几个节点不直接相连的情况下使其值的和最大。

思路和代码

最开始的思路我是采用自顶向下递归遍历树的形式来计算可能获得的最大收益。当前节点的情况有两种:选中或是没选中,如果选中的话,那么两个直接子节点将不可以被选中,如果没选中,那么两个直接子节点的状态可以是选中或是没选中。代码如下:

代码语言:javascript
复制
    public int rob(TreeNode root) {
        if(root == null) return 0;
        int result1 = root.val + (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right)) + (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right));
        int result2 = rob(root.left) + rob(root.right);
        return Math.max(result1, result2);
    }

这段代码的缺陷在于,我需要遍历这棵树两次,分别为了获取选中当前节点和不选中当前节点的情况。而事实上我们可以在一次遍历中就得到这两个情况对于当前节点的影响,并通过递归将值传递回上一层。很像是一种逆向思维。

代码语言:javascript
复制
    public int rob2(TreeNode root) {
        if (root == null) return 0;
        int[] value = robSum(root);
        return Math.max(value[0], value[1]);
    }
    
    private int[] robSum(TreeNode root) {
        int[] res = new int[2];
        if (root == null) return res;
        
        int[] left = robSum(root.left);
        int[] right = robSum(root.right);
        
        res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        res[1] = root.val + left[0] + right[0];
        
        return res;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档