LeetCode 题解工作台
新 21 点
爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如下: 爱丽丝以 0 分开始,并在她的得分少于 k 分时抽取数字。 抽取时,她从 [1, maxPts] 的范围中随机获得一个整数作为分数进行累计,其中 maxPts 是一个整数。 每次抽取都是独立的,其结果具有相同的概率。 当爱丽丝获得 …
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 ,表示当前分数为 时,到最终停止抽取数字时,分数不超过 的概率。那么答案就是 。 函数 的计算方法如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如下:
爱丽丝以 0 分开始,并在她的得分少于 k 分时抽取数字。 抽取时,她从 [1, maxPts] 的范围中随机获得一个整数作为分数进行累计,其中 maxPts 是一个整数。 每次抽取都是独立的,其结果具有相同的概率。
当爱丽丝获得 k 分 或更多分 时,她就停止抽取数字。
爱丽丝的分数不超过 n 的概率是多少?
与实际答案误差不超过 10-5 的答案将被视为正确答案。
示例 1:
输入:n = 10, k = 1, maxPts = 10 输出:1.00000 解释:爱丽丝得到一张牌,然后停止。
示例 2:
输入:n = 6, k = 1, maxPts = 10 输出:0.60000 解释:爱丽丝得到一张牌,然后停止。 在 10 种可能性中的 6 种情况下,她的得分不超过 6 分。
示例 3:
输入:n = 21, k = 17, maxPts = 10 输出:0.73278
提示:
0 <= k <= n <= 1041 <= maxPts <= 104
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示当前分数为 时,到最终停止抽取数字时,分数不超过 的概率。那么答案就是 。
函数 的计算方法如下:
- 如果 ,那么停止抽取数字,如果 ,返回 ,否则返回 ;
- 否则,可以在 范围内抽取下一个数字 ,那么 。
这里我们可以使用记忆化搜索来加速计算。
以上方法的时间复杂度为 ,会超出时间限制,我们需要优化一下。
当 时,以下等式成立:
当 时,以下等式成立:
因此,当 时,我们将等式 减去等式 ,得到:
即:
如果 ,有:
我们假设有 个数不超过 ,那么 ,又因为 ,所以 ,因此等式 可以写成:
综上所述,有以下状态转移方程:
时间复杂度 ,空间复杂度 。其中 为最大分数。
class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
@cache
def dfs(i: int) -> float:
if i >= k:
return int(i <= n)
if i == k - 1:
return min(n - k + 1, maxPts) / maxPts
return dfs(i + 1) + (dfs(i + 1) - dfs(i + maxPts + 1)) / maxPts
return dfs(0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) using sliding window accumulation for dp, and space complexity is O(n) to store the DP array. Without sliding window optimization, naive DP would be O(n*maxPts). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate defines dp[x] clearly and explains why each state depends on previous maxPts states.
- question_mark
Candidate optimizes naive DP using a sliding window to reduce time complexity.
- question_mark
Candidate correctly handles edge cases like k = 0 or n < k without overcounting probabilities.
常见陷阱
外企场景- error
Attempting naive summation of all prior states for each dp[x], leading to TLE.
- error
Forgetting to cap the probability sum at n, causing overestimation.
- error
Not accounting for k = 0, which should immediately return 1.0 probability.
进阶变体
外企场景- arrow_right_alt
Change maxPts to a non-uniform probability distribution for each draw, requiring weighted DP.
- arrow_right_alt
Compute expected value instead of probability, altering the DP recurrence slightly.
- arrow_right_alt
Consider multiple players drawing sequentially, updating DP to track joint probabilities.