House Robber III问题

House Robber III问题

对于一棵二叉树,要求找到一些节点,这些节点互相之间不直接相邻,且其和值最大(原题见最后)。

思路

从单个节点出发,对每个节点而言只有两种情况,即:被选略过

对于节点p而言,考虑以p点作为根节点的子树的情况:
f1(p)为p点被选时的子树最大和值; f2(p)为p点被略过时的最大和值。

  1. p点被选时,它相邻的左右子节点plpr则不能被选,有:
    f1(p) = val(p) + f2(pl) + f2(pr)
  2. p点没有入选时,它的左右子节点可以被选也可以略去,取最大值,有:
    f2(p) = max(f2(pl) + f2(pr), f1(pl) + f1(pr), f1(pl) + f2(pr), f2*(pl) + f1(pr))

通过递归遍历二叉树即可得解。

参考代码:

/**
 * 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:
    int rob(TreeNode* root) {
        pair<int, int> p = subMax(root);
        return max(p.first, p.second);
    }
    pair<int, int> subMax(TreeNode* root){
        if(!root){return make_pair(0, 0);}
        int r1, r2;
        pair<int, int> rl = subMax(root->left);
        pair<int, int> rr = subMax(root->right);
        r1 = root->val + rl.second + rr.second;
        r2 = max(max(rl.first + rr.first, rl.second + rr.second), max(rl.first + rr.second, rl.second + rr.first));
        // cout<<r1<<r2<<endl;
        return make_pair(r1, r2);
    }
};

原题如下:
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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值