131. Palindrome Partitioning (题目链接)
Medium
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
方法1:
class Solution:
def partition(self, s: str) -> List[List[str]]:
rlt = []
def isPalindrome(s: str):
return s == s[::-1]
def dfs(start: int, partitions: List[str]):
if start == len(s):
rlt.append(copy.deepcopy(partitions))
return
for i in range(start, len(s)):
if isPalindrome(s[start: i + 1]):
partitions.append(s[start:i + 1])
dfs(i + 1, partitions)
partitions.pop()
dfs(0, [])
return rlt
方法2:对方法1进行优化
因为我们在判断是否是回文的时候,会判断很多重复的字符串是否是回文,我们用动态规划记录下所有用到的可能的字符串是否是回文
其实就是利用了[LeeCode] 5. Longest Palindromic Substring
class Solution:
def partition(self, s: str) -> List[List[str]]:
rlt = []
dp = [[False] * len(s) for i in range(len(s))]
for j in range(len(s)):
for i in range(j + 1):
if i == j:
dp[i][j] = True
elif j - 1 == i:
dp[i][j] = s[i] == s[j]
else:
dp[i][j] = dp[i + 1][j - 1] and s[i] == s[j]
def dfs(start: int, partitions: List[str]):
if start == len(s):
rlt.append(copy.deepcopy(partitions))
return
for i in range(start, len(s)):
if dp[start][i]:
partitions.append(s[start:i + 1])
dfs(i + 1, partitions)
partitions.pop()
dfs(0, [])
return rlt