leetcode更新题目,又是一个入室盗窃。。。。
题目如下:
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "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 forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
跟入室盗窃系列1和2差不多的思想,动态规划即可。然而,这个是树,不能像以前一样,一个vector+遍历搞定(事实上,不需要一个数组,两个int即可,一个记录前一个最大值,一个计记录前前个最大值)。
怎么办呢?思想一样,记录当前节点最大值以及当前节点下一层的最大值。因为是树,得递归,而且一次返回两个参数,不妨用结构体。用结构体保存两个参数,层层递归即可。
结构体定义如下:
typedef struct maxMoney{
int now;//全局最优,即包含根节点的最优
int pre;//不含根节点最优,即根节点下一层左子树和右子数的全局最优之和
}MAXMONEY;
CPP可AC代码如下:
class Solution {
public:
typedef struct maxMoney{
int now;//全局最优
int pre;//不含根节点最优
}MAXMONEY;
int max(int a,int b){
return a>b?a:b;
}
MAXMONEY robmoney(TreeNode* root){
MAXMONEY money;
money.now=0;
money.pre=0;
if (root==NULL)//空节点则返回值均为0
return money;
MAXMONEY moneyleft=robmoney(root->left);//递归求左子树
MAXMONEY moneyright=robmoney(root->right);//递归求右子树
money.now=max((root->val+moneyleft.pre+moneyright.pre),(moneyleft.now+moneyright.now));//全局最优
money.pre=moneyleft.now+moneyright.now;//不含根节点的最优
return money;
}
int rob(TreeNode* root) {
MAXMONEY money=robmoney(root);
return money.now;
}
};