[LintCode] House Robber III 打家劫舍之三-阿里云开发者社区

开发者社区> 云计算> 正文

[LintCode] 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
3
/ \
2   3
\   \ 
3   1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
3
/ \
4   5
/ \   \ 
1   3   1
Maximum amount of money the thief can rob = 4 + 5 = 9.

LeetCode上的原题,请参见我之前的博客House Robber III 。

解法一:

class Solution {
public:
    int houseRobber3(TreeNode* root) {
        unordered_map<TreeNode*, int> m;
        return helper(root, m);
    }
    int helper(TreeNode *root, unordered_map<TreeNode*, int> &m) {
        if (!root) return 0;
        if (m.count(root)) return m[root];
        int val = 0;
        if (root->left) {
            val += helper(root->left->left, m) + helper(root->left->right, m);
        }
        if (root->right) {
            val += helper(root->right->left, m) + helper(root->right->right, m);
        }
        val = max(val + root->val, helper(root->left, m) + helper(root->right, m));
        m[root] = val;
        return val;
    }
};

解法二:

class Solution {
public:
    int houseRobber3(TreeNode* root) {
        vector<int> res = helper(root);
        return max(res[0], res[1]);
    }
    vector<int> helper(TreeNode *root) {
        if (!root) return {0, 0};
        vector<int> left = helper(root->left);
        vector<int> right = helper(root->right);
        vector<int> res{0, 0};
        res[0] = max(left[0], left[1]) + max(right[0], right[1]);
        res[1] = left[0] + right[0] + root->val;
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:打家劫舍之三[LintCode] House Robber III ,如需转载请自行联系原博主。

版权声明:本文首发在云栖社区,遵循云栖社区版权声明:本文内容由互联网用户自发贡献,版权归用户作者所有,云栖社区不为本文内容承担相关法律责任。云栖社区已升级为阿里云开发者社区。如果您发现本文中有涉嫌抄袭的内容,欢迎发送邮件至:developer2020@service.aliyun.com 进行举报,并提供相关证据,一经查实,阿里云开发者社区将协助删除涉嫌侵权内容。

分享:
云计算
使用钉钉扫一扫加入圈子
+ 订阅

时时分享云计算技术内容,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

其他文章