一、题目:
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串题目链接https://leetcode.cn/problems/palindrome-partitioning/description/
二、代码
class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
ans = []
path = []
def dfs(i):
if i == n:
ans.append(path[:])
return
for j in range(i, n):
word = s[i: j + 1]
if word == word[::-1]:
path.append(word)
dfs(j+1)
path.pop()
dfs(0)
return ans
定义额外的函数,在函数中,对目标位以后的位置遍历,如果【i:j】==【i:j:-1】,即这一段是回文的,先存储该字符串到tmp中,继续调用j+1后的函数,也是遍历。如果一旦i==n,即遍历到头了,则把存储的字符串矩阵append到ans中,并return。对每一次遍历循环,最后都要对tmp清空!!采用tmp.pop()恢复现场。