leetcode/notes/src/house-robber.md
Sainnhe Park b8d1550a43
All checks were successful
ci/woodpecker/push/test Pipeline was successful
Add house-robber
2023-02-09 18:23:44 +08:00

32 lines
973 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 打家劫舍
## [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); // 右
/*
然后在这里动态规划
*/
```