leetcode-808-Soup Servings
问题
There are two types of soup: type A and type B. Initially we have N
ml of each type of soup. There are four kinds of operations:
- Serve 100 ml of soup A and 0 ml of soup B
- Serve 75 ml of soup A and 25 ml of soup B
- Serve 50 ml of soup A and 50 ml of soup B
- Serve 25 ml of soup A and 75 ml of soup B
When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml’s of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.
1 | Example: |
Notes:
0 <= N <= 10^9
.- Answers within
10^-6
of the true value will be accepted as correct.
分析
这个问题要解决的问题有两个,一个是大数据集的问题,另一个是递归中避免重复计算的问题。
- 大数据集问题。几种操作中可以看出,A有直接倒出100ml的操作,而B没有直接倒出100ml的操作。因此,随着N的增加,A先倒光的概率将会逐渐增高。经过测试发现,当N等于 4800 时,答案为 0.99999 ,当N等于 4801 时,答案为 1.00000。因此,当输入的N大于4800时可以直接返回1.00000,这样就解决了大数据集的问题。
- 避免重复计算问题。可以使用hashmap来避免重复计算,但比hashmap更高效的还是使用线性表来进行统计。因为每次操作的基本单元都是25ml,因此,我们可以将数据针对25ml进行缩放,然后使用二维数组来进行统计。
代码1
1 | class Solution { |
代码2
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/28/leetcode-808/
License: 知识共享署名-非商业性使用 4.0 国际许可协议