Here is a standard function to print the permutations of characters of a string:
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s
", a);
else
{
for (j = i; j < n; j++) //check till end of string
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
It works fine but there is a problem, it also prints some duplicate permutations, exapmle:
if string is "AAB"
the output is:
AAB
ABA
AAB
ABA
BAA
BAA
This is having 3 duplicate entries as well.
Can there be a way to prevent this to happen?
--
Thanks
Alok Kr.
See Question&Answers more detail:os