1void permute(string a, int l, int r)
2{
3 // Base case
4 if (l == r)
5 cout<<a<<endl;
6 else
7 {
8 // Permutations made
9 for (int i = l; i <= r; i++)
10 {
11
12 // Swapping done
13 swap(a[l], a[i]);
14
15 // Recursion called
16 permute(a, l+1, r);
17
18 //backtrack
19 swap(a[l], a[i]);
20 }
21 }
22}
1void perm(char a[], int level){
2
3 static int flag[10] = {0};
4 static char res[10];
5 // If we are the last character of the input string
6 if(a[level] == '\0'){
7 // First we assign stopping point to result
8 res[level] = '\0';
9 // Now we print everything
10 for(int i = 0; res[i] != '\0'; ++i){
11 printf("%c", res[i]);
12 }
13 printf("\n");
14 ++counter;
15 }
16 else{
17 // Scan the original string and flag to see what letters are available
18 for(int i = 0; a[i] != '\0'; ++i){
19 if(flag[i] == 0){
20 res[level] = a[i];
21 flag[i] = 1;
22 perm(a, level + 1);
23 flag[i] = 0;
24 }
25 }
26 }
27}
28
29int main(){
30 char first[] = "abc";
31 perm(first, 0);
32 return 0;
33}
1void permutation(string s)
2{
3 sort(s.begin(),s.end());
4 do{
5 cout << s << " ";
6 }
7 while(next_permutation(s.begin(),s.end()); // std::next_permutation
8
9 cout << endl;
10}