【leetcode】337. House Robber III
作者:互联网
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root
.
Besides the root
, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root
of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Example 1:
class Solution {
private:
int res=0;
public:
int rob(TreeNode* root) {
// 二叉树的动态规划
// 首先需要遍历二叉树 然后计算最大的偷盗金额 用递归来遍历二叉树 用数组来存储状态
//dp[0,1] dp[0] 包含当前节点的最大值 ;dp[1] 不包含当前节点的最大值
vector<int>dp=digui(root);
return max(dp[0],dp[1]);
}
vector<int> digui(TreeNode*node){
vector<int> dp(2,0);
if(node==nullptr) return dp;
vector<int> left=digui(node->left);
vector<int> right=digui(node->right);
dp[0]=left[1]+right[1]+node->val; //从最底层往上算
dp[1]=max(left[0],left[1])+max(right[0],right[1]);
return dp;
}
};
标签:node,right,return,House,337,root,III,dp,left 来源: https://www.cnblogs.com/aalan/p/15645029.html