原题
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”]
]
解法
DFS + backtracking
代码
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
def dfs(s, path, res):
if not s:
res.append(path)
return
for i in range(len(s)):
if isPal(s[:i+1]):
dfs(s[i+1:], path+[s[:i+1]], res)
def isPal(s):
return s == s[::-1]
res = []
dfs(s,[],res)
return res