solution 1 dynamic programming
This problem is similar to the idea of the classic dynamic programming problem "Climbing Stairs".
Let dp[i]
represents the probability that Alice can accumulate to i
points. Think about how we can reach i
points from the last state, then we can conclude that dp[i] = dp[i-W] * 1/W + ... + dp[i-1] * 1/W
. Now we can implement the algorithm based on the above formula.
double new21Game(int N, int K, int W) {
if(K == 0 || N >= K + W) return 1.0;
vector<double> dp(N + 1, 0);
dp[0] = 1.0;
double wSum = 1.0, res = 0.0;
for(int i = 1; i <= N; i++) {
dp[i] = wSum / W;
if(i < K) {
wSum += dp[i];
} else {
res += dp[i]; //we will only accumulate the probability for points that are no less than K
}
if(i - W >= 0) {
wSum -= dp[i-W];
}
}
return res;
}
网友评论