So the question was to make a function that prints all permutations of a given string and stores them in an arraylist. My code was as follows:
import java.util.ArrayList;
class Solution
{
public static void permutations (String str, String perms, ArrayList<String> sets){
// base case
if(str.length() == 0){
sets.add(perms);
return;
} // end of base case
for(int i =0; i<str.length(); i++){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i)+ str.substring(i+1);
permutations(newStr, perms+currentChar, sets);
return;
}// end of for
} // end of permutations() function
public static void main(String args[]){
ArrayList<String> sets = new ArrayList<>();
permutations("ABC", "", sets);
System.out.println(sets);
}// end of main
}// end of class
The issue I'm facing is that the ArrayList is storing only the first variation; i.e, only ABC and none of the others. I've been trying to find out the error for quite a while but cannot find it. Would be glad if someone helps out :)
P.S. Here is a code that does not use an ArrayList to store the variations and directly prints them. This code is working as it should:
/*Q) recursive function to print all the permutations of a string*/
class Permutations{
public static void printPerms(String str, String permutation){
// base case
if(str.length()==0){
System.out.println(permutation);
return;
}// end of base case
for(int i = 0; i<str.length(); i++){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i)+ str.substring(i+1);
printPerms(newStr, permutation+currentChar);
} // end of for
} // end of printPerms
public static void main(String args[]){
String str = "abc";
printPerms(str, "");
} // end of main()
}// end of class
return
only needs to be executed in the base case when all the characters in current iteration have been visited.
But in your example, code is returning after calling the printPerms
function, so after processing 1 iteration for char at 0, it returns and doesn't process any other characters in the string.
Remove/comment the return statement in the for
loop.
for(int i =0; i<str.length(); i++){
char currentChar = str.charAt(i);
String newStr = str.substring(0,i)+ str.substring(i+1);
printPerms(newStr, perms+currentChar, sets);
//return;
}// end of for