public class Solution {
public static List<List<String>> partition(String s) {
int len = s.length();
List<List<String>>[] result = new List[len + 1];
result[0] = new ArrayList<List<String>>();
result[0].add(new ArrayList<String>());
boolean[][] pair = new boolean[len][len];
for (int i = 0; i < s.length(); i++) {
result[i + 1] = new ArrayList<List<String>>();
for (int left = 0; left <= i; left++) {
if (s.charAt(left) == s.charAt(i) && (i-left <= 1 || pair[left + 1][i - 1])) {
pair[left][i] = true;
String str = s.substring(left, i + 1);
for (List<String> r : result[left]) {
List<String> ri = new ArrayList<String>(r);
ri.add(str);
result[i + 1].add(ri);
}
}
}
}
return result[len];
}
}
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.length() < 1) return res;
int len = s.length();
boolean[][] dp = new boolean[len][len];
for (int i = len - 1; i >= 0; i--) {
for (int j = i; j < len; j++) {
if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) {
dp[i][j] = true;
}
}
}
backtracking(s, 0, dp, new ArrayList<>(), res);
return res;
}
public void backtracking(String s, int start, boolean[][] dp, List<String> temp, List<List<String>> res) {
if (start == s.length()) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = start; i < s.length(); i++) {
if (dp[start][i]) {
temp.add(s.substring(start, i + 1));
backtracking(s, i + 1, dp, temp, res);
temp.remove(temp.size() - 1);
}
}
}
}
public class Solution {
private boolean isPalindrome(StringBuilder sb) {
if (sb.length() < 2) return true;
int i = 0;
int j = sb.length() - 1;
while (i < j) {
if (sb.charAt(i) != sb.charAt(j)) return false;
i++;
j--;
}
return true;
}
private void helper(char[] str, int idx, List<String> temp, List<List<String>> res) {
if (idx == str.length) {
res.add(new ArrayList<String>(temp));
}
StringBuilder sb = new StringBuilder();
for (int i = idx; i < str.length; i++) {
sb.append(str[i]);
if (isPalindrome(sb)) {
temp.add(sb.toString());
helper(str, i + 1, temp, res);
temp.remove(temp.size() - 1);
}
}
}
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.length() < 1) return res;
helper(s.toCharArray(), 0, new ArrayList<String>(), res);
return res;
}
}