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/1700-1799/1745.Palindrome Partitioning IV/README_EN.md
+60-19
Original file line number
Diff line number
Diff line change
@@ -54,7 +54,26 @@ tags:
54
54
55
55
<!-- solution:start -->
56
56
57
-
### Solution 1
57
+
### Solution 1: Dynamic Programming
58
+
59
+
We define $f[i][j]$ to indicate whether the substring of $s$ from the $i$-th character to the $j$-th character is a palindrome, initially $f[i][j] = \textit{true}$.
60
+
61
+
Then we can calculate $f[i][j]$ using the following state transition equation:
62
+
63
+
$$
64
+
f[i][j] = \begin{cases}
65
+
\textit{true}, & \text{if } s[i] = s[j] \text{ and } (i + 1 = j \text{ or } f[i + 1][j - 1]) \\
66
+
\textit{false}, & \text{otherwise}
67
+
\end{cases}
68
+
$$
69
+
70
+
Since $f[i][j]$ depends on $f[i + 1][j - 1]$, we need to enumerate $i$ from large to small and $j$ from small to large, so that when calculating $f[i][j]$, $f[i + 1][j - 1]$ has already been calculated.
71
+
72
+
Next, we enumerate the right endpoint $i$ of the first substring and the right endpoint $j$ of the second substring. The left endpoint of the third substring can be enumerated in the range $[j + 1, n - 1]$, where $n$ is the length of the string $s$. If the first substring $s[0..i]$, the second substring $s[i+1..j]$, and the third substring $s[j+1..n-1]$ are all palindromes, then we have found a feasible partitioning scheme and return $\textit{true}$.
73
+
74
+
After enumerating all partitioning schemes, if no valid partitioning scheme is found, return $\textit{false}$.
75
+
76
+
Time complexity is $O(n^2)$, and space complexity is $O(n^2)$. Where $n$ is the length of the string $s$.
58
77
59
78
<!-- tabs:start -->
60
79
@@ -64,13 +83,13 @@ tags:
64
83
classSolution:
65
84
defcheckPartitioning(self, s: str) -> bool:
66
85
n =len(s)
67
-
g= [[True] * n for _ inrange(n)]
86
+
f= [[True] * n for _ inrange(n)]
68
87
for i inrange(n -1, -1, -1):
69
88
for j inrange(i +1, n):
70
-
g[i][j] = s[i] == s[j] and (i +1== j org[i +1][j -1])
89
+
f[i][j] = s[i] == s[j] and (i +1== j orf[i +1][j -1])
0 commit comments