Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

1
2
3
4
5
6
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> list = new ArrayList<>();
dfs(list, new ArrayList<>(), s, 0);
return list;
}

public void dfs(List<List<String>> list, List<String> arr, String s, int start) {
if (start == s.length()) list.add(new ArrayList<>(arr));
else {
for (int i = start; i < s.length(); ++i) {
if (isPalindrome(s, start, i)) {
arr.add(s.substring(start, i + 1));
dfs(list, arr, s, i + 1);
arr.remove(arr.size() - 1);
}
}
}
}

public boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start++) != s.charAt(end--)) return false;
}
return true;
}
}