What is an elegant way to find all the permutations of a string. E.g. permutation for ba
, would be ba
and ab
, but what about longer st
This is what I did through basic understanding of Permutations and Recursive function calling. Takes a bit of time but it's done independently.
public class LexicographicPermutations {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="abc";
Listcombinations=new ArrayList();
combinations=permutations(s);
Collections.sort(combinations);
System.out.println(combinations);
}
private static List permutations(String s) {
// TODO Auto-generated method stub
Listcombinations=new ArrayList();
if(s.length()==1){
combinations.add(s);
}
else{
for(int i=0;itemp=permutations(s.substring(0, i)+s.substring(i+1));
for (String string : temp) {
combinations.add(s.charAt(i)+string);
}
}
}
return combinations;
}}
which generates Output as [abc, acb, bac, bca, cab, cba]
.
Basic logic behind it is
For each character, consider it as 1st character & find the combinations of remaining characters. e.g. [abc](Combination of abc)->
.
a->[bc](a x Combination of (bc))->{abc,acb}
b->[ac](b x Combination of (ac))->{bac,bca}
c->[ab](c x Combination of (ab))->{cab,cba}
And then recursively calling each [bc]
,[ac]
& [ab]
independently.