Welcome to Subscribe On Youtube
1230. Toss Strange Coins
Description
You have some coins. The i
-th coin has a probability prob[i]
of facing heads when tossed.
Return the probability that the number of coins facing heads equals target
if you toss every coin exactly once.
Example 1:
Input: prob = [0.4], target = 1 Output: 0.40000
Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0 Output: 0.03125
Constraints:
1 <= prob.length <= 1000
0 <= prob[i] <= 1
0 <= target
<= prob.length
- Answers will be accepted as correct if they are within
10^-5
of the correct answer.
Solutions
Solution 1: Dynamic Programming
Let
Consider
where
We note that the state
The time complexity is
-
class Solution { public double probabilityOfHeads(double[] prob, int target) { int n = prob.length; double[][] f = new double[n + 1][target + 1]; f[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= Math.min(i, target); ++j) { f[i][j] = (1 - prob[i - 1]) * f[i - 1][j]; if (j > 0) { f[i][j] += prob[i - 1] * f[i - 1][j - 1]; } } } return f[n][target]; } }
-
class Solution { public: double probabilityOfHeads(vector<double>& prob, int target) { int n = prob.size(); double f[n + 1][target + 1]; memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j <= min(i, target); ++j) { f[i][j] = (1 - prob[i - 1]) * f[i - 1][j]; if (j > 0) { f[i][j] += prob[i - 1] * f[i - 1][j - 1]; } } } return f[n][target]; } };
-
class Solution: def probabilityOfHeads(self, prob: List[float], target: int) -> float: n = len(prob) f = [[0] * (target + 1) for _ in range(n + 1)] f[0][0] = 1 for i, p in enumerate(prob, 1): for j in range(min(i, target) + 1): f[i][j] = (1 - p) * f[i - 1][j] if j: f[i][j] += p * f[i - 1][j - 1] return f[n][target]
-
func probabilityOfHeads(prob []float64, target int) float64 { n := len(prob) f := make([][]float64, n+1) for i := range f { f[i] = make([]float64, target+1) } f[0][0] = 1 for i := 1; i <= n; i++ { for j := 0; j <= i && j <= target; j++ { f[i][j] = (1 - prob[i-1]) * f[i-1][j] if j > 0 { f[i][j] += prob[i-1] * f[i-1][j-1] } } } return f[n][target] }
-
function probabilityOfHeads(prob: number[], target: number): number { const n = prob.length; const f = new Array(n + 1).fill(0).map(() => new Array(target + 1).fill(0)); f[0][0] = 1; for (let i = 1; i <= n; ++i) { for (let j = 0; j <= target; ++j) { f[i][j] = f[i - 1][j] * (1 - prob[i - 1]); if (j) { f[i][j] += f[i - 1][j - 1] * prob[i - 1]; } } } return f[n][target]; }