题目:给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
或许是很久没写递归回溯的缘故,最近面对这类题目有点陌生。看了下题解思路,慢慢回忆起了递归回溯的写法,感觉和DFS的写法其实很类似。
解法一:回溯
借个大佬的图:
但凡回溯问题,一般画个图思路就清晰了。代码如下:
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
length = len(s)
def digui(s, temp):
if not s:
res.append(temp[:])
return
for i in range(len(s)):
left = s[:i+1]
if left == left[::-1]: #此处判断是否回文串,可以进一步优化
temp.append(left)
digui(s[i+1:], temp)
temp.pop() #回溯的体现
else:
continue
digui(s, [])
return res
执行结果:通过显示详情
执行用时 :88 ms, 在所有 Python3 提交中击败了74.72%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了34.75%的用户
解法二:回溯+DP
解法一中判断是否回文串,每次都有正反比较,是相对耗时的地方。在第5题:判断是否回文串中,使用DP法将每个闭区间是否是回文先判断出来。
但是这里的DP Table很讨厌,每次都需要想清楚Table的行列分别代表什么东西,容易混淆,尤其在使用DP Table进行判断时也容易混淆行、列的意义。
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
length = len(s)
dp = [[False for i in range(length)] for j in range(length)]
for i in range(length):
for j in range(i+1):
if s[i] == s[j] and (i-j<=2 or dp[j+1][i-1]):
dp[j][i] = True
# print(dp)
def digui(n, temp):
nonlocal length
if n > length-1:
res.append(temp[:])
return
for i in range(n, length):
left = s[n:i+1]
if dp[n][i]:
temp.append(left)
digui(i+1, temp)
temp.pop()
else:
continue
digui(0, [])
return res
执行结果:通过显示详情
执行用时 :72 ms, 在所有 Python3 提交中击败了93.65%的用户
内存消耗 :13.6 MB, 在所有 Python3 提交中击败了12.73%的用户
此时也要注意改变递归的传参形式,不能像解法一中那样简单切片传参,而要利用字符串索引作为参数传递。