方法一:递归
超时!
class Solution {
public:
int rob(TreeNode* root) {
if(!root)
return 0;
int res=root->val;
if(root->left)
res+=rob(root->left->left)+rob(root->left->right);
if(root->right)
res+=rob(root->right->left)+rob(root->right->right);
return max(res,rob(root->left)+rob(root->right));
}
};
方法二:用哈希表改进
解决重复子问题,超时!
class Solution {
private:
int helper(TreeNode* root,map<TreeNode*,int> mp){
if(!root)
return 0;
if(mp.find(root)!=mp.end())
return mp[root];
int res=root->val;
if(root->left)
res+=helper(root->left->left,mp)+helper(root->left->right,mp);
if(root->right)
res+=helper(root->right->left,mp)+helper(root->right->right,mp);
res=max(res,helper(root->left,mp)+helper(root->right,mp));
mp.insert({root,res});
return res;
}
public:
int rob(TreeNode* root) {
map<TreeNode*,int> mp;
return helper(root,mp);
}
};
方法三:
用一个pair分别记录包含根节点和不包含根节点时的最大值
class Solution {
private:
pair<int,int> helper(TreeNode* root){
if(!root)
return {0,0};
auto left = helper(root->left);
auto right = helper(root->right);
return {max(left.first, left.second) + max(right.first, right.second),left.first+ right.first + root->val};
}
public:
int rob(TreeNode* root) {
auto res=helper(root);
return max(res.first,res.second);
}
};