题目
思路
dfs+dp。
判断一个字符串的所有子串是否为回文,可以用dp来加快计算。如果
s[i]==s[j],dp[i][j]=dp[i+1][j−1]
s
[
i
]
==
s
[
j
]
,
d
p
[
i
]
[
j
]
=
d
p
[
i
+
1
]
[
j
−
1
]
代码
class Solution(object):
def __init__(self):
self.res_list = []
def dfs(self, startIndex, s, num_list, dp):
if startIndex == len(s):
self.res_list.append(num_list[:])
else:
for endIndex in range(startIndex, len(s)):
if dp[startIndex][endIndex]:
num_list.append(s[startIndex:endIndex + 1])
self.dfs(endIndex + 1, s, num_list, dp)
num_list.pop(-1)
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
dp = [[0 for i in range(len(s))] for j in range(len(s))]
for i in range(len(s))[::-1]:
for j in range(i, len(s)):
if i == j: dp[i][j] = 1
else:
if s[i] == s[j]:
if j == i + 1 or dp[i + 1][j - 1] == 1:
dp[i][j] = 1
self.dfs(0, s, [], dp)
return self.res_list