Re: [閒聊] 每日LeetCode

作者: Rushia (みけねこ的鼻屎)   2023-07-29 16:35:42
https://leetcode.com/problems/soup-servings/description/
808. Soup Servings
你現在有兩種湯要分給一群人,給你一個 n 表示這兩種湯的 ml 數量,我們有四種分湯
的方法:
1.A分出100ml B分出0ml
2.A分出75ml B分出25ml
3.A分出50ml B分出50ml
4.A分出25ml B分出75ml
求出依照上述四種分湯的方法,A種類的湯會先被分完的機率,如果A和B同時分完則機率
是50%。
Example 1:
Input: n = 50
Output: 0.62500
Explanation: If we choose the first two operations, A will become empty first.
For the third operation, A and B will become empty at the same time.
For the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability
that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) =
0.625.
Example 2:
Input: n = 100
Output: 0.71875
思路:
1.對四個選擇進行DFS,如果滿足A先沒的話機率就為1,如果同時沒則機率為0.5。
2.加入一個 memo 記憶已算過的分配比率。
3.然後吃了MLE = = ,實在是不懂要怎麼繼續優化,看了一下其他人的解當 n 越大
的時候,A被先分配完的機率會越來越高(因為分配方式2/3對A有利),因為題目
說實際答案和你給的答案相差在 10^-5 之間可以接受 ,所以當 n 大到一個程度
的時候機率會是 0.99999xxxxxx 這個時候我們直接返回 1 就可以了,只能一個數
字一個數字跑看跑到哪個 n 之後精度可以忽略,當 n = 4450 的時候誤差為:
1 - 0.9999893866772255 = 0.00001061332 ,所以當 n 高於這個數字直接返回
1 就好。
Java Code:

Links booklink

Contact Us: admin [ a t ] ucptt.com