File tree Expand file tree Collapse file tree 1 file changed +15
-18
lines changed Expand file tree Collapse file tree 1 file changed +15
-18
lines changed Original file line number Diff line number Diff line change @@ -259,33 +259,30 @@ class Solution:
259259class 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
You can’t perform that action at this time.
0 commit comments