public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null) return res;
dfs(res, new ArrayList<String>(), 0, s);
return res;
}
public static void dfs(List<List<String>> res, ArrayList<String> list, int start, String s) {
if (start == s.length()) {
res.add(new ArrayList<String>(list));
return;
}
for (int i = start; i < s.length(); i++) {
String sub = s.substring(start, i + 1);
if (!isPalindrome(sub)) {
continue;
}
list.add(sub);
dfs(res, list, i + 1, s);
list.remove(list.size() - 1);
}
}
public static boolean isPalindrome(String s) {
if (s == null || s.length() == 0) return false;
if (s.length() == 1) return true;
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)){
return false;
}
start++;
end--;
}
return true;
}