Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0e5bfda

Browse files
committed
improved code of palindrome-partitioning
1 parent 625b934 commit 0e5bfda

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed

‎advanced_algorithm/backtrack.md

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -259,33 +259,30 @@ class Solution:
259259
class Solution:
260260
def partition(self, s: str) -> List[List[str]]:
261261

262-
n = len(s)
263-
is_Pal = {}
262+
N = len(s)
263+
Pal = collections.defaultdict(set)
264264

265265
def isPal(i, j):
266266
if i < j:
267-
return is_Pal[i, j]
267+
return j in Pal[i]
268268
return True
269269

270-
for i in range(n - 2, -1, -1):
271-
for j in range(i + 1, n):
272-
is_Pal[i, j] = s[i] == s[j] and isPal(i + 1, j - 1)
270+
for j in range(N):
271+
for i in range(j + 1):
272+
if s[i] == s[j] and isPal(i + 1, j - 1):
273+
Pal[i].add(j)
273274

274275
result = []
275276

276-
def backtrack(left=-1, right=-1, route=[]):
277-
278-
if not isPal(left, right):
279-
return
280-
281-
if right == n - 1:
282-
result.append(route.copy())
277+
def backtrack(first=0, route=[]):
278+
279+
if first == N:
280+
result.append(route[:])
283281
return
284-
285-
left = right + 1
286-
for i in range(left, n):
287-
route.append(s[left:i + 1])
288-
backtrack(left, i, route)
282+
283+
for i in Pal[first]:
284+
route.append(s[first:i+1])
285+
backtrack(i + 1)
289286
route.pop()
290287

291288
return

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /