For example, if the input string is “ABC”, then output should be “ABC, ACB, BAC, BCA, CAB, CBA”.
Here is my approach :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void print(char str[],int visited[],int index,char temp[],int len)
{
if(index==len)
{
temp[index]='\0';
printf("\n%s",temp);
return;
}
for(int i=0;i<len;i++)
{
if(!visited[str[i]-'A'])
{
visited[str[i]-'A']=1;
temp[index]=str[i];
print(str,visited,index+1,temp,len);
visited[str[i]-'A']=0;
}
}
}
int main()
{
int visited[20]={0};
char temp[20];
char str[] = "ABCD";
int len=strlen(str);
print(str,visited,0,temp,len);
getch();
return 0;
}
I have made use of a visited array to avoid repetition of characters. What will be the complexity of this code?
std::next_permutation
. – Rapptz