Description
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
参考题解画出回溯树容易理解代码。
class Solution:
def partition(self, s: str) -> List[List[str]]:
res = []
def backtrack(i, tmp):
if i == len(s): res.append(tmp[:])
for j in range(i, len(s)):
if s[i:j+1] == s[i:j+1][::-1]:
tmp.append(s[i:j+1])
backtrack(j+1,tmp)
tmp.pop()
backtrack(0, [])
# print(res)
return res