LeetCode 题解工作台
解决智力问题
给你一个下标从 0 开始的二维整数数组 questions ,其中 questions[i] = [points i , brainpower i ] 。 这个数组表示一场考试里的一系列题目,你需要 按顺序 (也就是从问题 0 开始依次解决),针对每个问题选择 解决 或者 跳过 操作。解决问题 i …
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 ,表示从第 个问题开始解决,能够获得的最高分数。那么答案就是 。 函数 的计算方式如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的二维整数数组 questions ,其中 questions[i] = [pointsi, brainpoweri] 。
这个数组表示一场考试里的一系列题目,你需要 按顺序 (也就是从问题 0 开始依次解决),针对每个问题选择 解决 或者 跳过 操作。解决问题 i 将让你 获得 pointsi 的分数,但是你将 无法 解决接下来的 brainpoweri 个问题(即只能跳过接下来的 brainpoweri 个问题)。如果你跳过问题 i ,你可以对下一个问题决定使用哪种操作。
- 比方说,给你
questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:- 如果问题
0被解决了, 那么你可以获得3分,但你不能解决问题1和2。 - 如果你跳过问题
0,且解决问题1,你将获得4分但是不能解决问题2和3。
- 如果问题
请你返回这场考试里你能获得的 最高 分数。
示例 1:
输入:questions = [[3,2],[4,3],[4,4],[2,5]] 输出:5 解释:解决问题 0 和 3 得到最高分。 - 解决问题 0 :获得 3 分,但接下来 2 个问题都不能解决。 - 不能解决问题 1 和 2 - 解决问题 3 :获得 2 分 总得分为:3 + 2 = 5 。没有别的办法获得 5 分或者多于 5 分。
示例 2:
输入:questions = [[1,1],[2,2],[3,3],[4,4],[5,5]] 输出:7 解释:解决问题 1 和 4 得到最高分。 - 跳过问题 0 - 解决问题 1 :获得 2 分,但接下来 2 个问题都不能解决。 - 不能解决问题 2 和 3 - 解决问题 4 :获得 5 分 总得分为:2 + 5 = 7 。没有别的办法获得 7 分或者多于 7 分。
提示:
1 <= questions.length <= 105questions[i].length == 21 <= pointsi, brainpoweri <= 105
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从第 个问题开始解决,能够获得的最高分数。那么答案就是 。
函数 的计算方式如下:
- 如果 ,表示已经解决完所有问题,返回 ;
- 否则,设第 个问题的分数为 ,需要跳过的问题数为 ,那么 。
为了避免重复计算,我们可以使用记忆化搜索的方法,用一个数组 记录所有已经计算过的 的值。
时间复杂度 ,空间复杂度 。其中 是问题的数量。
class Solution:
def mostPoints(self, questions: List[List[int]]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(questions):
return 0
p, b = questions[i]
return max(p + dfs(i + b + 1), dfs(i + 1))
return dfs(0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates a good understanding of dynamic programming with state transitions.
- question_mark
The candidate chooses an appropriate method (memoization or tabulation) for solving the problem efficiently.
- question_mark
The candidate identifies and handles edge cases, such as when it's better to skip questions based on brainpower costs.
常见陷阱
外企场景- error
Not considering the effect of skipping questions and failing to track the maximum points across both choices.
- error
Forgetting to store computed results (memoization) or using inefficient recursive calls without dynamic programming.
- error
Improperly handling large input sizes, leading to time complexity issues without optimization.
进阶变体
外企场景- arrow_right_alt
Introduce varying brainpower costs for different questions and check if the approach remains optimal.
- arrow_right_alt
Modify the problem to include additional constraints such as limited time to solve questions.
- arrow_right_alt
Adapt the problem to allow solving multiple questions at once, complicating the decision process.