Home > other >  Leetcode 131, backtracking algorithm segmentation problem of palindrome string
Leetcode 131, backtracking algorithm segmentation problem of palindrome string

Time:01-23

Everybody is good, in a recent study, backtracking algorithm did leetcode 131 questions, questions as follows:

Given a string s, a string, s divided into some to make each substring is palindrome string,

Return s all possible segmentation scheme,

Example:

Input: "aab
"Output:

[" aa ", "b"],
[" a ", "a", "b"]
]


I wrote two code, in my opinion the thinking of these two kinds of code should be the same, are standard back in the enumeration method, but I don't know why, after the operation results of the first approach is always returns null, the second is can pass, but just don't know why two practice will produce different results (in my opinion the first practice even more standard), want to consult the BBS great god help to look at, thank you for your help!!!!!

The first approach:
The class Solution:
Def partition (self, s: STR) - & gt; The List [the List [STR]] :
Res, ans=[], []
Def backtrack (s) :
If len (s)==0:
Res. Append (ans)
Return
For I in range (len (s)) :
If s [: I + 1)==s [: I + 1] [: : 1] :
Ans. Append (s [: I + 1])
Backtrack (s/I + 1:)
Ans. Pop ()
Backtrack (s)
Return res

Return results:
Input: "aab
"Output:

[],
[]
]

The second approach:
The class Solution:
Def partition (self, s: STR) - & gt; The List [the List [STR]] :
Res, ans=[], []
Def back (ans, s) :
If len (s)==0 # status meet the requirements of the final
Res. Append (ans) # to join the results
Return
For I in range (0, len (s)) :
If s [: I + 1)==s [: I + 1] [: : 1] :
Back (ans + [s] [: I + 1], the s/I + 1:)
The back (ans, s)
Return res
Input: "aab
"Output:

[" aa ", "b"],
[" a ", "a", "b"]
]
  • Related