Simple Java Solution : (BackTracking)


#1

public class Solution {
ArrayList<ArrayList> res = new ArrayList<>();
public ArrayList<ArrayList> partition(String s) {
ArrayList sub = new ArrayList<>();
getPalindromePartitions(s,0,sub);
return res;
}
public void getPalindromePartitions(String s,int in,ArrayList sub){
if(in>=s.length()){
res.add(new ArrayList<>(sub));
return;
}
for(int i=in;i<s.length();i++){
String str = s.substring(in,i+1);
if(checkPalindrome(str)){
sub.add(str);
getPalindromePartitions(s,i+1,sub);
sub.remove(sub.size()-1);
}
}
}
public boolean checkPalindrome(String str){
for(int i=0,j=str.length()-1;i<j;i++,j–){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
}
return true;
}

}