You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/0800-0899/0837.New 21 Game/README_EN.md
+91-5Lines changed: 91 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -68,7 +68,81 @@ In 6 out of 10 possibilities, she is at or below 6 points.
68
68
69
69
<!-- solution:start -->
70
70
71
-
### Solution 1
71
+
### Solution 1: Memoized Search
72
+
73
+
We design a function $dfs(i)$, which represents the probability that when the current score is $i$, the final score does not exceed $n$ when we stop drawing numbers. The answer is $dfs(0)$.
74
+
75
+
The calculation method of function $dfs(i)$ is as follows:
76
+
77
+
- If $i \ge k$, then we stop drawing numbers. If $i \le n$, return $1$, otherwise return $0$;
78
+
- Otherwise, we can draw the next number $j$ in the range $[1,..\textit{maxPts}]$, then $dfs(i) = \frac{1}{maxPts} \sum_{j=1}^{maxPts} dfs(i+j)$.
79
+
80
+
Here we can use memoized search to accelerate the calculation.
81
+
82
+
The time complexity of the above method is $O(k \times \textit{maxPts})$, which will exceed the time limit, so we need to optimize it.
We assume there are $i$ numbers not exceeding $n$, then $k+i-1 \leq n$, and since $i\leq \textit{maxPts}$, we have $i \leq \min(n-k+1, \textit{maxPts})$, so equation $(3)$ can be written as:
function new21Game(n:number, k:number, maxPts:number):number {
175
-
const f=newArray(k).fill(0);
249
+
const f:number[] =Array(k).fill(0);
176
250
const dfs = (i:number):number=> {
177
251
if (i>=k) {
178
252
returni<=n?1:0;
@@ -195,7 +269,19 @@ function new21Game(n: number, k: number, maxPts: number): number {
195
269
196
270
<!-- solution:start -->
197
271
198
-
### Solution 2
272
+
### Solution 2: Dynamic Programming
273
+
274
+
We can convert the memoized search in Solution 1 into dynamic programming.
275
+
276
+
Define $f[i]$ to represent the probability that when the current score is $i$, the final score does not exceed $n$ when we stop drawing numbers. The answer is $f[0]$.
277
+
278
+
When $k \leq i \leq \min(n, k + \textit{maxPts} - 1)$, we have $f[i] = 1$.
279
+
280
+
When $i = k - 1$, we have $f[i] = \min(n-k+1, \textit{maxPts}) / \textit{maxPts}$.
281
+
282
+
When $i \lt k - 1$, we have $f[i] = f[i + 1] + (f[i + 1] - f[i + \textit{maxPts} + 1]) / \textit{maxPts}$.
283
+
284
+
Time complexity $O(k + \textit{maxPts})$, space complexity $O(k + \textit{maxPts})$. Where $k$ is the maximum score.
199
285
200
286
<!-- tabs:start -->
201
287
@@ -283,7 +369,7 @@ function new21Game(n: number, k: number, maxPts: number): number {
0 commit comments