★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ybwluxyv-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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:git
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.github
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. spa
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.
Notes:code
0 <= N <= 10^9
. 10^-6
of the true value will be accepted as correct.有 A 和 B 两种类型的汤。一开始每种类型的汤有 N
毫升。有四种分配操做:htm
当咱们把汤分配给某人以后,汤就没有了。每一个回合,咱们将从四种几率同为0.25的操做中进行分配选择。若是汤的剩余量不足以完成某次操做,咱们将尽量分配。当两种类型的汤都分配完时,中止操做。blog
注意不存在先分配100 ml汤B的操做。rem
须要返回的值: 汤A先分配完的几率 + 汤A和汤B同时分配完的几率 / 2。get
示例: 输入: N = 50 输出: 0.625 解释: 若是咱们选择前两个操做,A将首先变为空。对于第三个操做,A和B会同时变为空。对于第四个操做,B将首先变为空。 因此A变为空的总几率加上A和B同时变为空的几率的一半是 0.25 *(1 + 1 + 0.5 + 0)= 0.625。
注释:
0 <= N <= 10^9
。返回值在 10^-6
的范围将被认为是正确的。
1 class Solution { 2 var m:[String:Double] = [String:Double]() 3 func soupServings(_ N: Int) -> Double { 4 return N >= 4800 ? 1.0 : f(N, N) 5 } 6 7 func f(_ a:Int,_ b:Int) ->Double 8 { 9 if a <= 0 && b <= 0 {return 0.5} 10 if a <= 0 {return 1.0} 11 if b <= 0 {return 0} 12 var spoon:String = String(a) + ":" + String(b) 13 if m[spoon] == nil 14 { 15 m[spoon] = 0.25 * (f(a - 100, b) + f(a - 75, b - 25) + f(a - 50, b - 50) + f(a - 25, b - 75)) 16 } 17 return m[spoon]! 18 } 19 }
72ms
1 class Solution { 2 var mark = [String : Double]() 3 func soupServings(_ N: Int) -> Double { 4 return N > 4800 ? 1 : distributeSoup(N, N) 5 } 6 7 func distributeSoup(_ a: Int, _ b: Int) -> Double { 8 let key = "\(a),\(b)" 9 if let rate = mark[key] { 10 return rate 11 } 12 13 if a <= 0 { 14 if b > 0 { 15 return 1 16 } else { 17 return 0.5 18 } 19 } else { 20 if b <= 0 { 21 return 0 22 } 23 } 24 25 let distribute = distributeSoup(a - 100, b) 26 + distributeSoup(a - 75, b - 25) 27 + distributeSoup(a - 50, b - 50) 28 + distributeSoup(a - 25, b - 75) 29 mark[key] = distribute * 0.25 30 return mark[key] ?? 0 31 } 32 }