[LeetCode] 337. House Robber III

来源:互联网 发布:什么软件可以做动漫 编辑:程序博客网 时间:2024/06/05 00:51

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.

// useless(pretty slow) but clear    int rob(TreeNode* root) {        if (root == nullptr) return 0;        int ll, lr , rl, rr, l, r;        ll = lr = rl = rr = l = r = 0;        if (root->left) {            ll = rob(root->left->left);            lr = rob(root->left->right);        }        if (root->right) {            rl = rob(root->right->left);            rr = rob(root->right->right);        }        l = rob(root->left);        r = rob(root->right);        return max(root->val + ll + lr + rl + rr, l + r);    }
// using unordered_map to hash calculated resultclass Solution {public:    int rob(TreeNode* root) {        unordered_map<TreeNode *, int> map;        return __rob(root, map);    }private:    int __rob(TreeNode *root, unordered_map<TreeNode *, int> &map) {        if (root == nullptr) return 0;        if (map.find(root) != map.end())            return map[root];        int ll, lr , rl, rr, l, r;        ll = lr = rl = rr = l = r = 0;        if (root->left) {            ll = __rob(root->left->left, map);            lr = __rob(root->left->right, map);        }        if (root->right) {            rl = __rob(root->right->left, map);            rr = __rob(root->right->right, map);        }        l = __rob(root->left, map);        r = __rob(root->right, map);        int res = max(root->val + ll + lr + rl + rr, l + r);        map[root] = res;        return res;    }};

这里写图片描述