I'm aware of handling the issue with duplicates if I were to use a swap and permute method for generating permutations as shown here.
However, I'm using a different approach where I place current character between any two characters, at the beginning and at the end, of all of the permutations generated without the current character.
How can I modify my code below to give me only unique permutations in a string that contains duplicates
import java.util.ArrayList;
public class Permutations {
public static void main(String[] args) {
String str = "baab";
System.out.println(fun(str, 0));
System.out.println("number of Permutations =="+fun(str, 0).size());
}
static ArrayList<String> fun(String str, int index)
{
if(index == str.length())
{
ArrayList<String> al = new ArrayList<String>();
al.add("");
return al;
}
/* get return from lower frame */
ArrayList<String> rec = fun(str, index+1);
/* get character here */
char c = str.charAt(index);
/* to each of the returned Strings in ArrayList, add str.charAt(j) */
ArrayList<String> ret = new ArrayList<String>();
for(int i = 0;i<rec.size();i++)
{
String here = rec.get(i);
ret.add(c + here);
for(int j = 0;j<here.length();j++)
ret.add(here.substring(0,j+1) + c + here.substring(j+1,here.length()));
}
return ret;
}
}
At the moment, a string such as "bab" generates the following output, which contain abb and bba multiple times.
[bab, abb, abb, bba, bba, bab]
number of Permutations ==6
PS : I do not want to use a hashmap/Set to keep track of my duplicates and see whether they were encountered previously.