/*
Using Backtracking Algo to print all the permutations of a string
*/
#include "iostream"
using namespace std;
void permutate(int startIndex,int endIndex,char s[])
{
if (startIndex==endIndex)
{
cout<<s<<endl;
return;
}
for(int j=startIndex;j<=endIndex;j++)
{
char c = s[startIndex];
s[startIndex] = s[j];
s[j] = c;
permutate(startIndex+1,endIndex,s);
c = s[startIndex];
s[startIndex] = s[j];
s[j] = c;
}
}
int main()
{
// As a test case I have taken max length of string as 4.
//use std::string or vector<char> instead if dynamic length needed
char s[] = "ABCD";
permutate(0,3,s);
return 0;
}
No comments:
Post a Comment