阅读背景:

Leetcode 337. 打家劫舍 III 递归状态定义,记忆话搜索

来源:互联网 

如下代码,直接傻搜的话会超时。

class Solution {
public:
    unordered_map<TreeNode*,int> hashmap;
    int rob(TreeNode* root) {
        if(root==NULL) return 0;
       // if(hashmap.count(root)) return hashmap[root];
        int left = rob(root->left);
        int right = rob(root->right);
        int nextleft = (root->left==NULL?0:rob(root->left->left) + rob(root->left->right));
        int nextRight = (root->right==NULL?0:rob(root->right->left)+rob(root->right->right));
        //int res = max(left+right,root->val+nextleft+nextRight);
       // hashmap.insert({root,res});
       // return res;
        return max(left+right,root->val+nextleft+nextRight);
    }
};class Solution



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: