如下代码,直接傻搜的话会超时。
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);
}
};
增加一个hashmap,直接返回已经搜过点的答案,记忆话搜索。
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), 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;
}
};