leetcode 1230 - Toss Strange Coins

https://leetcode.com/problems/toss-strange-coins/

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* 2D space */
class Solution {
public:
double probabilityOfHeads(vector<double>& prob, int target) {
int n = prob.size();
vector<vector<double>> dp(n, vector<double>(target+2));

dp[0][0] = 1 - prob[0];
dp[0][1] = prob[0];

for (int i = 1; i < n; i++) {
for (int j = 0; j <= target; j++) {
dp[i][j] = dp[i-1][j] * (1 - prob[i]);
if (j > 0)
dp[i][j] += dp[i-1][j-1] * prob[i];
}
}

return dp[n-1][target];
}
};

/* 1D space */
class Solution {
public:
double probabilityOfHeads(vector<double>& prob, int target) {
int n = prob.size();
vector<double> dp(target+2);

dp[0] = 1 - prob[0];
dp[1] = prob[0];

for (int i = 1; i < n; i++) {
for (int j = 0; j <= target; j++) {
double tmp = dp[j] * (1 - prob[i]);
if (j > 0)
tmp += dp[j-1] * prob[i];
dp[j] = tmp;
}
}

return dp[target];
}
};