一、题目描述
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.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
题目解读:给出一棵二叉树,不能同时盗窃相邻的两个节点。求出最大收益。
思路:采用动态规划的思想,从根节点到叶子节点这样的顺序从上往下求出每个节点的最大收益。
设定pair<int, int>用来存储每个节点的状态,first 表示到达该节点的最大收益(已比较过盗窃和不盗窃该节点后得到的最大值),second表示不盗窃该节点的最大收益。因此有公式:
(1) rob_root = max( rob_L + rob_R, no_rob_L + no_rob_R + root->val)
(2) no_rob_root = rob_L + rob_R
rob_root :表示盗窃 root 节点, no_rob_L:表示不盗窃rob的左孩子节点
c++代码1:first 存储的是已比较了盗窃和不盗窃的最大收益(12ms,76.16%)
/**
* 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:
int rob(TreeNode* root) {
return dfs(root).first;
}
pair<int, int> dfs(TreeNode* root){
//该函数返回一个pair,first是到达root节点时的最大收益,second是不盗窃root节点的最大收益
pair<int, int> dp= make_pair(0,0);
if(root){
pair<int, int> dp_L=dfs(root->left);
pair<int, int> dp_R=dfs(root->right);
dp.second=dp_L.first+dp_R.first;
//不盗窃root,最大收益等于盗窃左孩子和右孩子的收益
dp.first = max(dp.second, dp_L.second+dp_R.second+root->val);
}//if
return dp;
}
};
c++代码2:first 存储的盗窃root节点的最大收益(20ms,41.03%)
/**
* 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:
int rob(TreeNode* root) {
pair<int, int> result=dfs(root);
return max(result.first, result.second);
}
pair<int, int> dfs(TreeNode* root){
//first是盗窃节点root的话可以得到的最大收益
//second是不盗窃节点root的话可以得到的最大收益
pair<int, int> dp=make_pair(0,0);
if(root){
pair<int, int> dp_L = dfs(root->left);
pair<int, int> dp_R = dfs(root->right);
dp.first = dp_L.second+dp_R.second+root->val;
//盗窃root = 不盗窃left + 不盗窃right + root的值
dp.second = max(dp_L.first, dp_L.second)+max(dp_R.first, dp_R.second);
}//if
return dp;
}
};