LeetCode 题解工作台
打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 …
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 ,表示从第 间房屋开始偷窃能够得到的最高金额。那么答案即为 。 函数 的执行过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例 1:
输入:[1,2,3,1] 输出:4 解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入:[2,7,9,3,1] 输出:12 解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
提示:
1 <= nums.length <= 1000 <= nums[i] <= 400
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从第 间房屋开始偷窃能够得到的最高金额。那么答案即为 。
函数 的执行过程如下:
- 如果 ,表示所有房屋都被考虑过了,直接返回 ;
- 否则,考虑偷窃第 间房屋,那么 ;不偷窃第 间房屋,那么 。
- 返回 。
为了避免重复计算,我们使用记忆化搜索的方法,将 的结果保存在一个数组或哈希表中,每次计算前先查询是否已经计算过,如果计算过直接返回结果。
时间复杂度 ,空间复杂度 。其中 是数组长度。
class Solution:
def rob(self, nums: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(nums):
return 0
return max(nums[i] + dfs(i + 2), dfs(i + 1))
return dfs(0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of state transition dynamic programming and its application to linear problems.
- question_mark
The candidate should be able to explain how dynamic programming optimizes the problem and how space can be minimized.
- question_mark
Assess whether the candidate is able to apply iterative thinking and bottom-up approach to dynamic programming problems.
常见陷阱
外企场景- error
Overcomplicating the solution by trying to include more than the last two houses in the dynamic programming calculation.
- error
Failing to handle edge cases like small arrays (length 1 or 2) correctly.
- error
Misunderstanding the state transitions, leading to incorrect logic for choosing whether to rob or skip a house.
进阶变体
外企场景- arrow_right_alt
Incorporating constraints such as a limited number of robberies (e.g., only robbing 'k' houses).
- arrow_right_alt
Extending the problem to include circular arrays where the first and last houses are adjacent.
- arrow_right_alt
Adjusting the problem to account for varying robbery costs or penalties for robbing certain houses.