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.

解法一:直接递归有很多duplication操作
考虑用dp,这里用一个数组保存已经知道的子树的rob()值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    map<TreeNode*,int> robmap;
    int rob(TreeNode* root) {

        if(root==NULL)return 0;
            if(robmap.find(root)!=robmap.end())return robmap[root];
            int ll=root->left?rob(root->left->left):0;
            int lr=root->left?rob(root->left->right):0;
            int rl=root->right?rob(root->right->left):0;
            int rr=root->right?rob(root->right->right):0;
            int res= max((root->val)+ll+lr+rl+rr,rob(root->left)+rob(root->right));
            robmap[root]=res;
            return res;
    }


    };

解法二:
考虑为什么会有那么多的duplication操作,因为计算rob(root)的时候要用到root下面两层子孙的值,因此考虑将root一层和root->son->son 一层进行decoupling,方法是让rob返回两个值,一个是包含自己的最大值一个是不包含自己的最大值,这样计算rob(root)的时候仅仅需要儿子一层的信息就可以

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值