House Robber III问题
对于一棵二叉树,要求找到一些节点,这些节点互相之间不直接相邻,且其和值最大(原题见最后)。
思路
从单个节点出发,对每个节点而言只有两种情况,即:被选和略过。
对于节点p而言,考虑以p点作为根节点的子树的情况:
令f1(p)为p点被选时的子树最大和值; f2(p)为p点被略过时的最大和值。
- 当p点被选时,它相邻的左右子节点pl和pr则不能被选,有:
f1(p) = val(p) + f2(pl) + f2(pr) - 当p点没有入选时,它的左右子节点可以被选也可以略去,取最大值,有:
f2(p) = max(f2(pl) + f2(pr), f1(pl) + f1(pr), f1(pl) + f2(pr), f2*(pl) + f1(pr))
通过递归遍历二叉树即可得解。
参考代码:
/**
* 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> p = subMax(root);
return max(p.first, p.second);
}
pair<int, int> subMax(TreeNode* root){
if(!root){return make_pair(0, 0);}
int r1, r2;
pair<int, int> rl = subMax(root->left);
pair<int, int> rr = subMax(root->right);
r1 = root->val + rl.second + rr.second;
r2 = max(max(rl.first + rr.first, rl.second + rr.second), max(rl.first + rr.second, rl.second + rr.first));
// cout<<r1<<r2<<endl;
return make_pair(r1, r2);
}
};
原题如下:
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.