I have written a recursive method using nested loops to print all permutations of a given string.It prints all the permutations but more than once can someone figure out the problem and what to change in conditions to solve this?
public static String swap(String x,int a,int b){
char list[]=x.toCharArray();
char tmp=x.charAt(a);
list[a]=list[b];
list[b]=tmp;
return new String(list);
}
public static void perm(String x,String base){
if(base.length()==3)
System.out.println(base);
for(int i=0;i<x.length();i++)
for(int j=i;j<x.length();j++){
String tmp=swap(x,i,j);
perm(tmp.substring(1),base+tmp.charAt(0));
}
}
Example: Input :"abc". Output: abc acb abc bac bca bac cba cab cba abc acb abc acb abc acb abc acb abc.