Movatterモバイル変換


[0]ホーム

URL:


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

Commit0e5bfda

Browse files
committed
improved code of palindrome-partitioning
1 parent625b934 commit0e5bfda

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
classSolution:
260260
defpartition(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
defisPal(i,j):
266266
if i< j:
267-
returnis_Pal[i, j]
267+
returnjin Pal[i]
268268
returnTrue
269269

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

274275
result= []
275276

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

291288
return

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp