leetcode-837-New 21 Game
问题
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:
1 | Input: N = 10, K = 1, W = 10 |
Example 2:
1 | Input: N = 6, K = 1, W = 10 |
Example 3:
1 | Input: N = 21, K = 17, W = 10 |
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.
分析
分析可知获得任意一个点的大小与前面的点的大小是有关系的。因此,我们可以自顶向下递归地求出每一个点的概率,然后将 大于等于 K,小于等于 N 的点的概率相加就可以得到答案。但如果不进行优化答案自然就会TLE,如代码1。分析可知,每个点依赖于其前面的W个点,在我们依次求出 $1-N$ 这些点的概率的时候其实是可以重复利用之前的结果,也就是我们一直维护待求点前的$W$ 个点的概率和,这样求解每一个点的概率的时间复杂度就是 $O(1)$,而不是 $O(W)$ 。
代码1
1 | class Solution { |
代码2
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/30/leetcode-837/
License: 知识共享署名-非商业性使用 4.0 国际许可协议