In the examples, we can see each char itself is palindrome. For aab, we have a, a and b. But then we have to break aab again to aa and b.
This is how the decision tree looks:
classSolution {
public List < List<String>>partition(String s) {
List < List<String>> ans =new ArrayList<>();
if (s ==null|| s.length() == 0) {
return ans;
}
//track each possible partition dfs(s, 0, new ArrayList<String>(), ans);
return ans;
}
privatevoiddfs(String s, int idx, List<String> subAns, List < List<String>> ans) {
//stop conditionif (idx == s.length()) {
ans.add(new ArrayList<String> (subAns));
return;
}
for (int i = idx; i < s.length(); i++) {
String str = s.substring(idx, i + 1);
if (isPalindrome(str)) {
subAns.add(str); // take the substr and store it in subAns & call the next substr from idx + 1 dfs(s, i + 1, subAns, ans);
subAns.remove(subAns.size() - 1); // remove the string, and try now with substr(idx, i + 2) for eg. }
}
}
privatebooleanisPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
returnfalse;
}
left++;
right--;
}
returntrue;
}
}