Add house-robber
All checks were successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
Sainnhe Park 2023-02-09 18:23:44 +08:00
parent b2dda568e2
commit b8d1550a43
2 changed files with 32 additions and 0 deletions

View File

@ -56,6 +56,7 @@
- [总结](./dynamic-programming.md) - [总结](./dynamic-programming.md)
- [基础问题](./dynamic-programming-basic.md) - [基础问题](./dynamic-programming-basic.md)
- [背包问题](./knapsack.md) - [背包问题](./knapsack.md)
- [打家劫舍](./house-robber.md)
# STL # STL

31
notes/src/house-robber.md Normal file
View File

@ -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<int> left = robTree(cur->left); // 左
vector<int> right = robTree(cur->right); // 右
/*
然后在这里动态规划
*/
```