19. House Robber III

Link to the problem

Description

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.

Idea

Use recursion with cache. If the root is chose, then you have to recurse on grandchildren. If it's not, then you recurse on children.

Solution

class Solution {
private:
    int robHelper(TreeNode *root, unordered_map<TreeNode*, int> &cache) {
        if (cache.find(root) != cache.end()) return cache[root];
        else if (!root) return 0;
        else {
            int choose = root->val, not_choose = 0;
            if (root->left) not_choose += robHelper(root->left, cache);
            if (root->right) not_choose += robHelper(root->right, cache);
            if (root->left && root->left->left) choose += robHelper(root->left->left, cache);
            if (root->left && root->left->right) choose += robHelper(root->left->right, cache);
            if (root->right && root->right->left) choose += robHelper(root->right->left, cache);
            if (root->right && root->right->right) choose += robHelper(root->right->right, cache);
            int rtn = max(choose, not_choose);
            cache[root] = rtn;
            return rtn;
        }
    }
public:
    int rob(TreeNode* root) {
        unordered_map<TreeNode*, int> cache;
        return robHelper(root, cache);
    }
};

124 / 124 test cases passed.
Runtime: 15 ms

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容