Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Input: s = "a"
Output: [["a"]]
Goal: Split string into parts where each part is a palindrome.
For "aab":
Approach: Try all possible splits, keep those where all parts are palindromes.
This is a Backtracking with Validation problem:
def backtrack(start, current):
if start == len(s):
result.append(current.copy())
return
for end in range(start + 1, len(s) + 1):
substring = s[start:end]
if is_palindrome(substring):
current.append(substring)
backtrack(end, current)
current.pop()
Optimization: Cache palindrome checks with DP.
Time: O(n × 2^n)
Space: O(n) recursion depth
1import java.util.*;
2
3class Solution {
4 public List<List<String>> partition(String s) {
5 List<List<String>> result = new ArrayList<>();
6 backtrack(s, 0, new ArrayList<>(), result);
7 return result;
8 }
9
10 private void backtrack(String s, int start, List<String> current, List<List<String>> result) {
11 if (start == s.length()) {
12 result.add(new ArrayList<>(current));
13 return;
14 }
15
16 for (int end = start + 1; end <= s.length(); end++) {
17 String substring = s.substring(start, end);
18 if (isPalindrome(substring)) {
19 current.add(substring);
20 backtrack(s, end, current, result);
21 current.remove(current.size() - 1);
22 }
23 }
24 }
25
26 private boolean isPalindrome(String s) {
27 int left = 0, right = s.length() - 1;
28 while (left < right) {
29 if (s.charAt(left++) != s.charAt(right--)) {
30 return false;
31 }
32 }
33 return true;
34 }
35}
36