unordered_map<node,int,hashNode,cmpNode> mp;
node 为key,int为value,
hashNode为自定义结构体的哈希函数(unordered_map就是通过这个值去查找的)
cmpNode比较函数(如果哈希值相同,怎么去处理不同的对象,也就是怎么解决冲突)
/**
* 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:
struct node{
TreeNode* root;
bool rob;
node(TreeNode *p,bool q):root(p),rob(q){}
};
struct hashNode{
size_t operator() (node a)const{
return hash<TreeNode*>()(a.root)^(a.rob==true?1:0);
}
};
struct cmpNode{
bool operator() (node a,node b)const{
return a.root==b.root&&a.rob==b.rob;
}
};
unordered_map<node,int,hashNode,cmpNode> mp;
int do_or_not(TreeNode* root,bool rob){
if(root==NULL) return 0;
node key(root,rob);
if(mp.count(key)==1) return mp[key];
int sum=0;
if(rob==true){
sum+=root->val;
sum+=do_or_not(root->left,false)+do_or_not(root->right,false);
}
else
sum=max(do_or_not(root->left,true),do_or_not(root->left,false))+max(do_or_not(root->right,true),do_or_not(root->right,false));
mp[key]=sum;
return sum;
}
int rob(TreeNode* root) {
return max(do_or_not(root,true),do_or_not(root,false));
}
};