【LeetCode】837. New 21 Game 解題報告(Python)
阿新 • • 發佈:2018-12-18
目錄
題目描述
Alice plays the following game, loosely based on the card game “21”.
Alice starts with 0
points, and draws numbers while she has less than K
points. During each draw, she gains an integer number of points randomly from the range [1, W]
, where W
is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets K
or more points. What is the probability that she has N
or less points?
Example 1:
Input: N = 10, K = 1, W = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.
Example 2:
Input: N = 6, K = 1, W = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of W = 10 possibilities, she is at or below N = 6 points.
Example 3:
Input: N = 21, K = 17, W = 10
Output: 0.73278
Note:
- 0 <= K <= N <= 10000
- 1 <= W <= 10000
- Answers will be accepted as correct if they are within 10^-5 of the correct answer. The judging time limit has been reduced for this question.
題目大意
剛開始的時候,有0分,她會已知在[1,W]中隨機選數字,直到有K分或者K分以上停止。問她能夠正好得到N分或者更少分的概率。
解題方法
動態規劃
類似爬樓梯的問題,每次可以跨[1,W]個樓梯,當一共爬了K個和以上的臺階時停止,問這個時候總檯階數<=N的概率。
使用動態規劃,dp[i]表示得到點數i的概率,只有當現在的總點數少於K的時候,才會繼續取數。那麼狀態轉移方程可以寫成:
- 當
i <= K
時,dp[i] = (前W個dp的和)/ W
;(爬樓梯得到總樓梯數為i的概率) - 當
K < i < K + W
時,那麼在這次的前一次的點數範圍是[i - W, K - 1]
。我們的dp陣列表示的是得到點i的概率,所以dp[i]=(dp[K-1]+dp[K-2]+…+dp[i-W])/W
.(可以從前一次的基礎的上選[1,W]個數字中的一個) - 當i>=K+W時,這種情況下無論如何不都應該存在的,所以dp[i]=0.
時間複雜度是O(N),空間複雜度是O(N).
class Solution(object):
def new21Game(self, N, K, W):
"""
:type N: int
:type K: int
:type W: int
:rtype: float
"""
if K == 0: return 1
dp = [1.0] + [0] * N
tSum = 1.0
for i in range(1, N + 1):
dp[i] = tSum / W
if i < K:
tSum += dp[i]
if 0 <= i - W < K:
tSum -= dp[i - W]
return sum(dp[K:])
相似題目
參考資料
日期
2018 年 11 月 1 日 —— 小光棍節