LeetCode 题解工作台
石子游戏 II
Alice 和 Bob 继续他们的石子游戏。许多堆石子 排成一行 ,每堆都有正整数颗石子 piles[i] 。游戏以谁手中的石子最多来决出胜负。 Alice 和 Bob 轮流进行,Alice 先开始。最初, M = 1 。 在每个玩家的回合中,该玩家可以拿走剩下的 前 X 堆的所有石子,其中 1 。…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
由于玩家每次可以拿走前 堆的所有石子,也就是说能拿走一个区间的石子,因此,我们可以先预处理出一个长度为 的前缀和数组 ,其中 表示数组 `piles` 的前 个元素的和。 然后我们设计一个函数 $dfs(i, m)$,表示当前轮到的人可以从数组 `piles` 的下标 开始拿,且当前的 为 时,当前轮到的人能够拿到的最大石子数。初始时爱丽丝从下标 开始,且 ,所以我们需要求的答案为…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
Alice 和 Bob 继续他们的石子游戏。许多堆石子 排成一行,每堆都有正整数颗石子 piles[i]。游戏以谁手中的石子最多来决出胜负。
Alice 和 Bob 轮流进行,Alice 先开始。最初,M = 1。
在每个玩家的回合中,该玩家可以拿走剩下的 前 X 堆的所有石子,其中 1 <= X <= 2M。然后,令 M = max(M, X)。
游戏一直持续到所有石子都被拿走。
假设 Alice 和 Bob 都发挥出最佳水平,返回 Alice 可以得到的最大数量的石头。
示例 1:
输入:piles = [2,7,9,4,4] 输出:10 解释:如果一开始 Alice 取了一堆,Bob 取了两堆,然后 Alice 再取两堆。Alice 可以得到 2 + 4 + 4 = 10 堆。 如果 Alice 一开始拿走了两堆,那么 Bob 可以拿走剩下的三堆。在这种情况下,Alice 得到 2 + 7 = 9 堆。返回 10,因为它更大。
示例 2:
输入:piles = [1,2,3,4,5,100] 输出:104
提示:
1 <= piles.length <= 1001 <= piles[i] <= 104
解题思路
方法一:前缀和 + 记忆化搜索
由于玩家每次可以拿走前 堆的所有石子,也就是说能拿走一个区间的石子,因此,我们可以先预处理出一个长度为 的前缀和数组 ,其中 表示数组 piles 的前 个元素的和。
然后我们设计一个函数 ,表示当前轮到的人可以从数组 piles 的下标 开始拿,且当前的 为 时,当前轮到的人能够拿到的最大石子数。初始时爱丽丝从下标 开始,且 ,所以我们需要求的答案为 。
函数 的计算过程如下:
- 如果当前轮到的人可以拿走剩下的所有石子,能够拿到的最大石子数为 ;
- 否则,当前轮到的人可以拿走剩下的前 堆的所有石子,其中 ,能够拿到的最大石子数为 。也即是说,当前轮的人能够拿到的石子数为当前剩下的所有石子数减去下一轮对手能够拿到的石子数。我们需要枚举所有的 ,取其中的最大值作为函数 的返回值。
为了避免重复计算,我们可以使用记忆化搜索。
最后,我们返回将 作为答案返回即可。
时间复杂度为 ,空间复杂度为 。其中 为数组 piles 的长度。
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
@cache
def dfs(i, m):
if m * 2 >= n - i:
return s[n] - s[i]
return max(
s[n] - s[i] - dfs(i + x, max(m, x)) for x in range(1, m << 1 | 1)
)
n = len(piles)
s = list(accumulate(piles, initial=0))
return dfs(0, 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assess the candidate’s understanding of dynamic programming and its application to game theory problems.
- question_mark
Look for the ability to design a solution with efficient memoization to handle multiple states.
- question_mark
Evaluate how well the candidate balances between recursion and optimization techniques for state transitions.
常见陷阱
外企场景- error
Failing to correctly implement the state transition, which can result in incorrect results or inefficient solutions.
- error
Overlooking the fact that the state space grows based on both the pile index and the maximum piles a player can take.
- error
Not optimizing the solution with memoization, leading to excessive recomputation and poor performance on larger inputs.
进阶变体
外企场景- arrow_right_alt
Consider modifying the game rules to allow players to take up to X piles, where X is a fixed number rather than based on M.
- arrow_right_alt
Change the problem to allow players to skip turns, requiring a more complex state transition.
- arrow_right_alt
Implement a variant where players can take stones from anywhere in the array rather than only starting from the first pile.