在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There are two types of soup: type A and type B. Initially we have
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. Notes:
有 A 和 B 两种类型的汤。一开始每种类型的汤有
当我们把汤分配给某人之后,汤就没有了。每个回合,我们将从四种概率同为0.25的操作中进行分配选择。如果汤的剩余量不足以完成某次操作,我们将尽可能分配。当两种类型的汤都分配完时,停止操作。 注意不存在先分配100 ml汤B的操作。 需要返回的值: 汤A先分配完的概率 + 汤A和汤B同时分配完的概率 / 2。 示例: 输入: N = 50 输出: 0.625 解释: 如果我们选择前两个操作,A将首先变为空。对于第三个操作,A和B会同时变为空。对于第四个操作,B将首先变为空。 所以A变为空的总概率加上A和B同时变为空的概率的一半是 0.25 *(1 + 1 + 0.5 + 0)= 0.625。 注释:
Runtime: 12 ms
Memory Usage: 19 MB
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 }
|
请发表评论