ETH官方钱包

切換
舊版
前往
大廳
主題

[LeetCode] 837. New 21 Game 欸久違的機(jī)率問題(我腦袋好爛)

テリ君(桃夫模式) | 2023-05-25 20:16:06 | 巴幣 4 | 人氣 267

題目:
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, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.

Alice stops drawing numbers when she gets k or more points.

Return the probability that Alice has n or fewer points.


class Solution(object):
    def new21Game(self, n, k, maxPts):
        # Corner cases
        if k == 0:
            return 1.0
        if n >= k - 1 + maxPts:
            return 1.0
        
        # dp[i] is the probability of getting point i.
        dp = [0.0] * (n + 1)
        # [0.0, 0.0, ..., 0.0] = (n + 1) * [0.0]

        probablity = 0.0 # dp of n or less point
        totalSum = 1.0 # sum of curr
        dp[0] = 1.0
        for i in range(1, n + 1):
            dp[i] = totalSum / maxPts

            if i < k:
                totalSum += dp[i]
            else:
                probablity += dp[i]

            if i >= maxPts:
                totalSum -= dp[i - maxPts]

        return probablity
    
sol = Solution()
print(sol.new21Game(21, 17, 10))

# time complexity = O(n)
# n is the range of the number, it's linear.

先初始化每個可能性的機(jī)率和總和dp,之後對每個dp做抽牌總和不大於n的機(jī)率,之後再把所有機(jī)率總合起來,就完事了。
不過腦袋要燒壞了,我覺得我需要找一件事情就認(rèn)真做到底,不然要沒生產(chǎn)力了。

時間複雜度為 O(n),其中 n 是遊戲中的數(shù)字範(fàn)圍。因?yàn)樵谵捜χ?,我們迭代了?1 到 n 的所有數(shù)字,並對每個數(shù)字執(zhí)行一些固定的操作。因此,整個程式的時間複雜度是線性的。

創(chuàng)作回應(yīng)

貓狗喵
這題BP超多,他機(jī)率不是條件機(jī)率,又有一堆定義詭異的test case
2023-05-25 21:29:50
テリ君(桃夫模式)
有我有看到,很納悶
2023-05-25 22:18:28
テリ君(桃夫模式)
我這題也是直接看人家submission去理解
2023-05-25 22:18:41

相關(guān)創(chuàng)作

更多創(chuàng)作