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/2400-2499/2478.Number of Beautiful Partitions/README_EN.md
+57-6
Original file line number
Diff line number
Diff line change
@@ -58,7 +58,30 @@
58
58
59
59
## Solutions
60
60
61
-
### Solution 1
61
+
### Solution 1: Dynamic Programming
62
+
63
+
We define $f[i][j]$ as the number of schemes for dividing the first $i$ characters into $j$ sections. Initialize $f[0][0] = 1$, and the rest $f[i][j] = 0$.
64
+
65
+
First, we need to determine whether the $i$th character can be the last character of the $j$th section, it needs to meet the following conditions simultaneously:
66
+
67
+
1. The $i$th character is a non-prime number;
68
+
1. The $i+1$th character is a prime number, or the $i$th character is the last character of the entire string.
69
+
70
+
If the $i$th character cannot be the last character of the $j$th section, then $f[i][j]=0$. Otherwise, we have:
71
+
72
+
$$
73
+
f[i][j]=\sum_{t=0}^{i-minLength}f[t][j-1]
74
+
$$
75
+
76
+
That is to say, we need to enumerate which character is the end of the previous section. Here we use the prefix sum array $g[i][j] = \sum_{t=0}^{i}f[t][j]$ to optimize the time complexity of enumeration.
77
+
78
+
Then we have:
79
+
80
+
$$
81
+
f[i][j]=g[i-minLength][j-1]
82
+
$$
83
+
84
+
The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$. Where $n$ and $k$ are the length of the string $s$ and the number of sections to be divided, respectively.
0 commit comments