From b8d1550a43e77f4c3f9fed6530cd53fbb10d1f7f Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Thu, 9 Feb 2023 18:23:44 +0800 Subject: [PATCH] Add house-robber --- notes/src/SUMMARY.md | 1 + notes/src/house-robber.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 notes/src/house-robber.md diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 73776a3..4763517 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -56,6 +56,7 @@ - [总结](./dynamic-programming.md) - [基础问题](./dynamic-programming-basic.md) - [背包问题](./knapsack.md) +- [打家劫舍](./house-robber.md) # STL diff --git a/notes/src/house-robber.md b/notes/src/house-robber.md new file mode 100644 index 0000000..a62558f --- /dev/null +++ b/notes/src/house-robber.md @@ -0,0 +1,31 @@ +# 打家劫舍 + +## [198. 打家劫舍](https://leetcode.cn/problems/house-robber/) + +- `dp[i]` 为考虑下标i(包括i)以内的房屋,最多可以偷窃的金额为 +- `dp[i] = max{dp[i - 2] + dp[i], dp[i - 1]}` +- `dp[0] = nums[0]`, `dp[1] = max{nums[0], nums[1]}`, 其它为 `0` +- 从前向后遍历 + +## [213. 打家劫舍II](https://leetcode.cn/problems/house-robber-ii/) + +和 s0198 差不多,只不过需要考虑三种情况: + +1. 只偷 `nums[0...i-1]` +2. 只偷 `nums[1...i]` +3. 只偷 `nums[1...i-1]` + +这三种情况取最大值即可。 + +## [337. 打家劫舍 III](https://leetcode.cn/problems/house-robber-iii/) + +递归遍历,递归函数的返回值是一个长度为 2 的数组,第一个元素为偷当前节点能偷到的最多的钱,第二个元素为不偷当前节点能够偷到的最多的钱。 + +```cpp +vector left = robTree(cur->left); // 左 +vector right = robTree(cur->right); // 右 + +/* + 然后在这里动态规划 +*/ +```