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/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md
+110-45
Original file line number
Diff line number
Diff line change
@@ -53,8 +53,8 @@ There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.
53
53
<strong>Input:</strong> n = 5, maxValue = 3
54
54
<strong>Output:</strong> 11
55
55
<strong>Explanation:</strong> The following are the possible ideal arrays:
56
-
- Arrays starting with the value 1 (9 arrays):
57
-
- With no other distinct values (1 array): [1,1,1,1,1]
56
+
- Arrays starting with the value 1 (9 arrays):
57
+
- With no other distinct values (1 array): [1,1,1,1,1]
58
58
- With 2<sup>nd</sup> distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]
59
59
- With 2<sup>nd</sup> distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]
60
60
- Arrays starting with the value 2 (1 array): [2,2,2,2,2]
@@ -76,7 +76,23 @@ There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.
76
76
77
77
<!-- solution:start -->
78
78
79
-
### Solution 1
79
+
### Solution 1: Dynamic Programming
80
+
81
+
Let $f[i][j]$ represent the number of sequences ending with $i$ and consisting of $j$ distinct elements. The initial value is $f[i][1] = 1$.
82
+
83
+
Consider $n$ balls, which are eventually divided into $j$ parts. Using the "separator method," we can insert $j-1$ separators into the $n-1$ positions, and the number of combinations is $c_{n-1}^{j-1}$.
84
+
85
+
We can preprocess the combination numbers $c[i][j]$ using the recurrence relation $c[i][j] = c[i-1][j] + c[i-1][j-1]$. Specifically, when $j=0$, $c[i][j] = 1$.
86
+
87
+
The final answer is:
88
+
\[
89
+
\sum\limits_{i=1}^{k}\sum\limits_{j=1}^{\log_2 k + 1} f[i][j] \times c_{n-1}^{j-1}
90
+
\]
91
+
92
+
where $k$ represents the maximum value of the array, i.e., $\textit{maxValue}$.
0 commit comments