leetcode 808. Soup Servings
原题地址:https://leetcode.com/problems/soup-servings/
题目
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:
- Serve 100 ml of soup A and 0 ml of soup B
- Serve 75 ml of soup A and 25 ml of soup B
- Serve 50 ml of soup A and 50 ml of soup B
- Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml’s of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
Example:
Input: N = 50
Output: 0.625
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.
Note:
- 0 <= N <= 10^9.
- Answers within 10^-6 of the true value will be accepted as correct.
python代码
class Solution:
dic = {}
def soupServings(self, N):
"""
:type N: int
:rtype: float
"""
if N >= 10000:
return 1.0
else:
return self.serve(N, N)
def serve(self, A, B):
if A == 0 and B != 0:
return 1.0
elif A == 0 and B == 0:
return 0.5
elif A != 0 and B == 0:
return 0.0
if (A, B) in self.dic.keys():
return self.dic[(A, B)]
prob = 0
prob += self.serve(A-min(A, 100), B) * 0.25
prob += self.serve(A-min(A, 75), B-min(B, 25)) * 0.25
prob += self.serve(A-min(A, 50), B-min(B, 50)) * 0.25
prob += self.serve(A-min(A, 25), B-min(B, 75)) * 0.25
self.dic[(A, B)] = prob
return prob
版权声明:转载注明 http://blog.youkuaiyun.com/birdreamer/article/details/79780412

本文针对LeetCode上的SoupServings问题进行了解析,通过递归概率计算方法来求解两个类型汤A和B同时被消耗完的概率问题。当剩余体积不足以完成操作时,将尽可能多地服务。最终返回汤A先耗尽的概率加上A和B同时耗尽的一半概率。
1476

被折叠的 条评论
为什么被折叠?



