|
58 | 58 |
|
59 | 59 | <!-- solution:start -->
|
60 | 60 |
|
61 |
| -### Solution 1 |
| 61 | +### Solution 1: Dynamic Programming |
| 62 | + |
| 63 | +First, we preprocess the string $s$ to determine whether each substring $s[i..j]$ is a palindrome, and record this in a 2D array $g[i][j]$, where $g[i][j]$ indicates whether the substring $s[i..j]$ is a palindrome. |
| 64 | + |
| 65 | +Next, we define $f[i]$ to represent the minimum number of cuts needed for the substring $s[0..i-1]$. Initially, $f[i] = i$. |
| 66 | + |
| 67 | +Next, we consider how to transition the state for $f[i]$. We can enumerate the previous cut point $j$. If the substring $s[j..i]$ is a palindrome, then $f[i]$ can be transitioned from $f[j]$. If $j = 0$, it means that $s[0..i]$ itself is a palindrome, and no cuts are needed, i.e., $f[i] = 0$. Therefore, the state transition equation is as follows: |
| 68 | + |
| 69 | +$$ |
| 70 | +f[i] = \min_{0 \leq j \leq i} \begin{cases} f[j-1] + 1, & \textit{if}\ g[j][i] = \textit{True} \\ 0, & \textit{if}\ g[0][i] = \textit{True} \end{cases} |
| 71 | +$$ |
| 72 | + |
| 73 | +The answer is $f[n]$, where $n$ is the length of the string $s$. |
| 74 | + |
| 75 | +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$. |
62 | 76 |
|
63 | 77 | <!-- tabs:start -->
|
64 | 78 |
|
@@ -178,17 +192,13 @@ func minCut(s string) int {
|
178 | 192 | ```ts
|
179 | 193 | function minCut(s: string): number {
|
180 | 194 | const n = s.length;
|
181 |
| - const g: boolean[][] = Array(n) |
182 |
| - .fill(0) |
183 |
| - .map(() => Array(n).fill(true)); |
| 195 | + const g: boolean[][] = Array.from({ length: n }, () => Array(n).fill(true)); |
184 | 196 | for (let i = n - 1; ~i; --i) {
|
185 | 197 | for (let j = i + 1; j < n; ++j) {
|
186 | 198 | g[i][j] = s[i] === s[j] && g[i + 1][j - 1];
|
187 | 199 | }
|
188 | 200 | }
|
189 |
| - const f: number[] = Array(n) |
190 |
| - .fill(0) |
191 |
| - .map((_, i) => i); |
| 201 | + const f: number[] = Array.from({ length: n }, (_, i) => i); |
192 | 202 | for (let i = 1; i < n; ++i) {
|
193 | 203 | for (let j = 0; j <= i; ++j) {
|
194 | 204 | if (g[j][i]) {
|
|
0 commit comments