计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
/**
* 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<TreeNode *, int> dp[2];
int dfs(TreeNode* now, int x){
if(dp[x].find(now) != dp[x].end()) return dp[x][now];
if(!now) return 0;
// x为1表示选中的当前点, 为0则不选当前点
int l0 = dfs(now->left, 0);
int l1 = dfs(now->left, 1);
int r0 = dfs(now->right, 0);
int r1 = dfs(now->right, 1);
if(x)
return dp[x][now] = (now->val + r0 + l0);
else
return dp[x][now] = (max(l0, l1) + max(r0, r1));
return -1;
}
int rob(TreeNode* root) {
int ans = max(dfs(root, 0), dfs(root, 1));
return ans;
}
};