给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:回溯法 注意回溯的位置
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
def help(s):
'''
判断s是否回文串
'''
i,j=0,len(s)-1
while i<=j:
if s[i]!=s[j]:
return False
else:
i+=1
j-=1
return True
def dfs(temp,s,start):
if start==len(s):
res.append(temp[:])
return
for i in range(start,len(s)):
if help(s[start:i+1]):
temp.append(s[start:i+1])
dfs(temp,s,i+1)
# 回溯
temp.pop()
res=[]
dfs([],s,0)
return res