This C++ Program demonstrates the generation of all Permutations using BackTracking.
Here is source code of the C++ Program to Generate All Permutations using BackTracking. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/** C++ Program to Generate All Permutations using BackTracking*/#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>using namespace std;
/* swap values at two pointers */void swap (char *x, char *y)
{char temp;
temp = *x;
*x = *y;
*y = temp;
}/* print permutations of string */void permute(char *a, int i, int n)
{int j;
if (i == n)
cout<<a<<endl;
else{for (j = i; j <= n; j++)
{swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a+i), (a + j));
}}}/* Main*/int main()
{char a[] = "abcd";
permute(a, 0, 3);
return 0;
}
$ g++ permutations_back.cpp $ a.out abcd abdc acbd acdb adcb adbc bacd badc bcad bcda bdca bdac cbad cbda cabd cadb cdab cdba dbca dbac dcba dcab dacb dabc ------------------ (program exited with code: 1) Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check Programming Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check Computer Science Books
- Practice Programming MCQs