在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Alice plays the following game, loosely based on the card game "21". Alice starts with Alice stops drawing numbers when she gets Example 1: Input: N = 10, K = 1, W = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: N = 6, K = 1, W = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of W = 10 possibilities, she is at or below N = 6 points. Example 3: Input: N = 21, K = 17, W = 10 Output: 0.73278 Note:
爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如下: 爱丽丝以 当爱丽丝获得不少于 示例 1: 输入:N = 10, K = 1, W = 10 输出:1.00000 说明:爱丽丝得到一张卡,然后停止。 示例 2: 输入:N = 6, K = 1, W = 10 输出:0.60000 说明:爱丽丝得到一张卡,然后停止。 在 W = 10 的 6 种可能下,她的得分不超过 N = 6 分。 示例 3: 输入:N = 21, K = 17, W = 10 输出:0.73278 提示:
24ms 1 class Solution { 2 func new21Game(_ N: Int, _ K: Int, _ W: Int) -> Double { 3 guard N > 0 else { return 1.0 } 4 guard W >= N - K else { return 1.0 } 5 var dp = Array(repeating: 0.0, count: N+1) 6 dp[0] = 1 7 let w = Double(W) 8 var temp = 0.0 9 for i in 1...N { 10 if i <= K { 11 temp += dp[i-1] / w 12 } 13 if i > W { 14 temp -= dp[i-W-1] / w 15 } 16 dp[i] = temp 17 } 18 return dp[K...].reduce(0.0, +) 19 } 20 } Runtime: 48 ms
Memory Usage: 18.8 MB
1 class Solution { 2 func new21Game(_ N: Int, _ K: Int, _ W: Int) -> Double { 3 if K == 0 || N >= (K + W) {return 1.0} 4 var dp:[Double] = [Double](repeating:0.0,count:K + W) 5 dp[0] = 1.0 6 for i in 1..<(K + W) 7 { 8 dp[i] = dp[i - 1] 9 if i <= W 10 { 11 dp[i] += dp[i - 1] / Double(W) 12 } 13 else 14 { 15 dp[i] += (dp[i - 1] - dp[i - W - 1]) / Double(W) 16 } 17 if i > K 18 { 19 dp[i] -= (dp[i - 1] - dp[K - 1]) / Double(W) 20 } 21 } 22 return dp[N] - dp[K - 1] 23 } 24 }
|
请发表评论