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 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:

1
2
3
4
5
3
/ \
2 3
\ \
3 1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

1
2
3
4
5
    3
/ \
4 5
/ \ \
1 3 1

Maximum amount of money the thief can rob = 4 + 5 = 9.

分析


这道题是House Robber的第三个版本,第一个版本是从一个序列中选择一些元素,使得和最大,但不能选择相邻的元素。第二个版本给定的序列是一个环,也就是说第一个不能和最后一个同时选。这道题的思路跟前面的版本是一致的,只不过跟树结合起来了,需要结合树的深度遍历的方式。

节点分窃取和不窃取两种情况,因此返回值是一个pair对象,包括两个值,第一个值是窃取了该节点的最大值,另外一个是不窃取该节点的最大值,在这两个值中取最大值。如果窃取了该节点,那么不能取该节点的左右子节点,值为:left.second+right.second+root->val,如果没有窃取该节点,值为左右节点能够窃取的最大值之和,值为:max(left.first, left.second)+max(right.first, right.second)。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 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 {

private:
pair<int, int> dp(TreeNode* root) {
if(root == NULL) {
return make_pair(0, 0);
}
auto left = dp(root->left);
auto right = dp(root->right);
int steal_node = left.second + right.second + root->val;
int not_steal_node = max(left.first, left.second) + max(right.first, right.second);
return make_pair(steal_node, not_steal_node);
}

public:
int rob(TreeNode* root) {
auto result = dp(root);
return max(result.first, result.second);
}
};

相关问题


(E) House Robber
(M) House Robber II

题目来源