func dicesProbability(_ n: Int) -> [Double] {
let sRangeMin = n
let sRangeMax = n * 6
var total = 0
var temp: [Int] = []
var res: [Double] = []
for s in sRangeMin...sRangeMax {
let c = resultCount(of: s, by: n)
total += c
temp.append(c)
}
temp.forEach {
res.append(Double($0) / Double(total))
}
return res
}
var dp: [String : Int] = [:]
/// 求 n 个 1-6 的数字和为 num 的组合数
/// - Parameters:
/// - num: -
/// - n: -
/// - Returns: 组合数
func resultCount(of num: Int, by n: Int) -> Int {
guard num >= n, num <= n*6 else { // 注意控制边界条件
return 0
}
guard n > 1 else {
return 1
}
let key = "\(n) - \(num)"
if let r = dp[key] {
return r
}
var res: Int = 0
for i in 1...6 {
res += resultCount(of: num - i, by: n - 1)
}
dp[key] = res
return res
}