枚举,最元素的位置可能隔两层,所以不是贪心。
树形dp其实就是同时返回两个结果,免得对同一个节点调用两次,免得对一个节点重复调用,使得后面出现重复。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> cal(TreeNode* root){//不取,取
if(root==NULL)
return {0,0};
auto left_ret=cal(root->left);
auto right_ret=cal(root->right);
int no=max(left_ret[0],left_ret[1])+max(right_ret[0],right_ret[1]);
int yes=root->val +left_ret[0]+right_ret[0];
return {no,yes};
}
int rob(TreeNode* root) {
if(root==NULL)
return 0;
auto ret=cal(root);
return max(ret[0],ret[1]);
}
};
枚举,和上面对比
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<string,int> record;
int cal(TreeNode* root,int mode){
if(root==NULL)
return 0;
string key=to_string((unsigned long long)root)+"|"+to_string(mode);
if(record.count(key)!=0)
return record[key];
if(mode==1){//可取
int sum1=root->val;
sum1+=cal(root->left,0);
sum1+=cal(root->right,0);
int sum2=0;
sum2+=cal(root->left,1);
sum2+=cal(root->right,1);
int ans=max(sum1,sum2);
record[key]=ans;
return ans;
}
else{//不可取
int sum=0;
sum+=cal(root->left,1);
sum+=cal(root->right,1);
record[key]=sum;
return sum;
}
}
int rob(TreeNode* root) {
if(root==NULL)
return 0;
return max(cal(root,0),cal(root,1));
}
};