-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path337-house-robber-iii.cpp
88 lines (81 loc) · 2.22 KB
/
337-house-robber-iii.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为
// root 。
//
// 除了
// root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的
//房子在同一天晚上被打劫 ,房屋将自动报警。
//
// 给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。
//
//
//
// 示例 1:
//
//
//
//
//输入: root = [3,2,3,null,3,null,1]
//输出: 7
//解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 7
//
// 示例 2:
//
//
//
//
//输入: root = [3,4,5,1,3,null,1]
//输出: 9
//解释: 小偷一晚能够盗取的最高金额 4 + 5 = 9
//
//
//
//
// 提示:
//
//
//
//
//
// 树的节点数在 [1, 10⁴] 范围内
// 0 <= Node.val <= 10⁴
//
//
// Related Topics 树 深度优先搜索 动态规划 二叉树 👍 1724 👎 0
#include "headers.h"
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob(TreeNode *root) {
// 树状DP
vector<int> res = robTree(root);
return max(res[0], res[1]);
}
// 后序遍历
vector<int> robTree(TreeNode *cur) {
if (cur == nullptr) return {0, 0};
vector<int> left = robTree(cur->left);
vector<int> right = robTree(cur->right);
// 可偷, 则左右都不可偷
int rob_cur = left[0] + right[0] + cur->val;
// 不可偷, 则左右各自找出最大价值情况
int not_rob_cur = max(left[0], left[1]) + max(right[0], right[1]);
return {not_rob_cur, rob_cur};
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
TreeNode root({3, 2, 3, -1, 3, -1, 1});
cout << s.rob(&root) << endl;
}