|
| 1 | +## House Robber III |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +Determine the maximum amount of money the thief can rob tonight without alerting the police. |
| 6 | + |
| 7 | +Example 1: |
| 8 | + |
| 9 | +``` |
| 10 | + 3 |
| 11 | + / \ |
| 12 | + 2 3 |
| 13 | + \ \ |
| 14 | + 3 1 |
| 15 | +``` |
| 16 | +Maximum amount of money the thief can `rob = 3 + 3 + 1 = 7`. |
| 17 | + |
| 18 | +Example 2: |
| 19 | + |
| 20 | +``` |
| 21 | + 3 |
| 22 | + / \ |
| 23 | + 4 5 |
| 24 | + / \ \ |
| 25 | + 1 3 1 |
| 26 | +``` |
| 27 | +Maximum amount of money the thief can `rob = 4 + 5 = 9`. |
| 28 | + |
| 29 | +## Solution |
| 30 | + |
| 31 | +最开始想到直接层次遍历,获取每一层的值,比如Example 2为`[3,9,5]`,然后转化为[House Robber](../HouseRobber)求解。时间复杂度时O(n),空间复杂度是O(n)。 |
| 32 | + |
| 33 | +看提示说使用DFS,一个节点要么选择要么不选择,设当前节点为p,yes为选择p节点的值,no为不选择p节点的值,f(p)为p节点的值,则: |
| 34 | + |
| 35 | +* 若p为null,则yes = 0, no = 0; |
| 36 | +* 若选择p,则不能选择p的孩子节点,则`p->yes = f(p->left->no) + f(p->right->no) + p->val`; |
| 37 | +* 若不选择p节点,则结果为孩子节点的最大值,即`p->no = max(f(p->left->yes), f(p->left->no)) + max(f(p->right->yes), f(p->right->no))` |
| 38 | + |
| 39 | +```cpp |
| 40 | +void dfs(TreeNode *root, int *yes, int *no) { |
| 41 | + if (root == nullptr) { |
| 42 | + *yes = 0; |
| 43 | + *no = 0; |
| 44 | + return; |
| 45 | + } |
| 46 | + int left_yes, left_no, right_yes, right_no; |
| 47 | + dfs(root->left, &left_yes, &left_no); |
| 48 | + dfs(root->right, &right_yes, &right_no); |
| 49 | + *yes = left_no + right_no + root->val; |
| 50 | + *no = max(left_yes, left_no) + max(right_yes, right_no); |
| 51 | +} |
| 52 | +``` |
| 53 | +
|
| 54 | +最后返回`max(root->yes, root->no)`即可。 |
| 55 | +
|
| 56 | +```cpp |
| 57 | +int rob(TreeNode *root) { |
| 58 | + int yes = 0, no = 0; |
| 59 | + dfs(root, &yes, &no); |
| 60 | + return max(yes, no); |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +## 参考 |
| 65 | + |
| 66 | +1. [House Robber](../HouseRobber) |
| 67 | +2. [House Robber II](../HouseRobberII) |
| 68 | +3. [House Robber III](../HouseRobberIII) |
0 commit comments