Cho mảng prob trong đó prob[i] là xác suất mặt ngửa của đồng xu thứ i. Tính xác suất có đúng target mặt ngửa khi tung tất cả đồng xu một lần.
Ví dụ: prob = [0.5,0.5,0.5,0.5,0.5], target = 0 → 0.03125.
Thuật toán giải quyết (Quy hoạch động)
dp[i][j] = xác suất có j mặt ngửa sau khi tung i+1 đồng xu đầu tiên.
n = prob.size(), tạo mảngdp[n][target+5].- Khởi tạo:
dp[0][0] = 1 - prob[0],dp[0][1] = prob[0]. - Với
i = 1 .. n-1:dp[i][0] = (1 - prob[i]) * dp[i-1][0].- Với
j = 1 .. min(i+1, target):dp[i][j] = (1-prob[i])*dp[i-1][j] + prob[i]*dp[i-1][j-1].
- Trả về
dp[n-1][target].
Ví dụ minh họa (C++)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
double probabilityOfHeads(vector<double>& prob, int target) {
int n = prob.size();
vector<vector<double>> dp(n, vector<double>(target + 5, 0));
dp[0][0] = 1 - prob[0];
if (target > 0) dp[0][1] = prob[0];
for (int i = 1; i < n; i++) {
dp[i][0] = (1 - prob[i]) * dp[i-1][0];
for (int j = 1; j <= min(i+1, target); j++) {
dp[i][j] = (1 - prob[i]) * dp[i-1][j] + prob[i] * dp[i-1][j-1];
}
}
return dp[n-1][target];
}
};
int main() {
vector<double> v = {0.5, 0.5, 0.5, 0.5, 0.5};
Solution ob;
cout << ob.probabilityOfHeads(v, 0);
}
Đầu vào
[0.5,0.5,0.5,0.5,0.5] 0
Đầu ra
0.03125