Hi,
I got this code for computing permutations of a string from the programming interviews exposed book. I am unable to think as to how recursion works in this case. Now, if the input string is "hat", then I have understood the sequence of recursive calls that lead to the printing of hat but am unable to figure out anything after that i.e. which statement is executed after returning from the recursive call. Could anyone help me understand this code?
int permutations(char *str)
{
int length, i, *used;
char *out;
length = strlen(str);
out = (char *)malloc(length+1);
if(!out)
return 0;
out[length] = '\0';
used = (int*)malloc(sizeof(int)*length);
if(!used)
return 0;
for(i=0;i<length;i++)
used[i]=0;
DoPermute(str, out, used, length, 0);
free(out);
free(used);
return 1;
}
void DoPermute(char *str, char* out, int* used, int length, int recursLev)
{
int i;
if(recursLev==length)
{
printf("%s\n", out);
return;
}
for(i=0;i<length;i++)
{
if(used[i])
continue;
out[recursLev] = str[i];
used[i] = 1;
DoPermute(str, out, used, length, recursLev+1);
used[i]=0;
}
}
Thanks all.