Alice plays the following game, loosely based on the card game "21".
Alice starts with 0
points, and draws numbers while she has less than K
points. During each draw, she gains an integer number of points randomly from the range [1, W]
, where W
is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets K
or more points. What is the probability that she has N
or less points?
Example 1:
Input: N = 10, K = 1, W = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops.
Example 2:
Input: N = 6, K = 1, W = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of W = 10 possibilities, she is at or below N = 6 points.
Example 3:
Input: N = 21, K = 17, W = 10 Output: 0.73278
Note:
0 <= K <= N <= 10000
1 <= W <= 10000
- Answers will be accepted as correct if they are within
10^-5
of the correct answer. - The judging time limit has been reduced for this question.
题目理解:
以均等概率抽W张卡片,卡片上分别有[1,W]分数,如果累计分数达到K,那么停止抽卡,问停止抽卡时,手中卡片的累计分数在[K,N]之间的概率
解题思路:
用一个一位数组存储卡片累计分数为x的概率,遍历抽到每一张卡片的情况
p[x] = p[x-i] * (1 / W), i = 1,2,3,...,W
最后返回K到N之间的概率和
这一题有更好的解法,p[x]不是代表卡片和为x的概率,而是卡片和为1,2,3,4,...x的概率的和
这里给出一般解法的代码
class Solution {
public double new21Game(int N, int K, int W) {
double[] record = new double[N + 1];
record[0] = 1;
double base = 1.0 / W;
for(int i = 1; i < N + 1; i++) {
int j = Math.max(0, i - W);
for(; j < i && j < K; j++) {
record[i] += record[j];
}
record[i] *= base;
}
double res = 0;
for(int i = K; i < N + 1; i++)
res += record[i];
return res;
}
}