32 lines
973 B
Markdown
32 lines
973 B
Markdown
|
# 打家劫舍
|
|||
|
|
|||
|
## [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<int> left = robTree(cur->left); // 左
|
|||
|
vector<int> right = robTree(cur->right); // 右
|
|||
|
|
|||
|
/*
|
|||
|
然后在这里动态规划
|
|||
|
*/
|
|||
|
```
|