PracticeNeetCode ↗LeetCode ↗
Given a string s, split it into substrings so every substring is a palindrome. Return all possible ways to do this.
sub == sub[::-1]) is enough to test for a palindrome; no separate DP table is needed unless performance demands it.isPalindrome(sub) using sub == sub[::-1].backtrack(start): if start == len(s), record a copy of path.end from start + 1 to len(s) + 1: let sub = s[start:end].isPalindrome(sub), append sub to path, recurse with backtrack(end), then pop.backtrack(0) and return the result.Time: O(n · 2ⁿ) worst case — Space: O(n) recursion depth
def partition(s: str) -> list[list[str]]:
result = []
path = []
def isPalindrome(sub: str) -> bool:
return sub == sub[::-1]
def backtrack(start: int) -> None:
if start == len(s):
result.append(path[:])
return
for end in range(start + 1, len(s) + 1):
sub = s[start:end]
if isPalindrome(sub):
path.append(sub)
backtrack(end)
path.pop()
backtrack(0)
return resultHow the solution above works, piece by piece.
backtrack(start) decides how to cut the rest of the string, s[start:].start == len(s), the whole string is split into palindromes: save a copy of path.sub = s[start:end] is the next piece.sub is a palindrome, add it, recurse from end, then pop. Non-palindromes prune the branch immediately.The recursion tree for s = "aab":