C++ Program to Print All Permutations using BackTracking

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.

  1. /*
  2.  * C++ Program to Generate All Permutations using BackTracking
  3.  */
  4. #include <iostream>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <cstdlib>
  8. using namespace std;
  9.  
  10. /* swap values at two pointers */
  11. void swap (char *x, char *y)
  12. {
  13.     char temp;
  14.     temp = *x;
  15.     *x = *y;
  16.     *y = temp;
  17. }
  18.  
  19. /* print permutations of string */
  20. void permute(char *a, int i, int n)
  21. {
  22.     int j;
  23.     if (i == n)
  24.         cout<<a<<endl;
  25.     else
  26.     {
  27.         for (j = i; j <= n; j++)
  28.         {
  29.             swap((a + i), (a + j));
  30.             permute(a, i + 1, n);
  31.             swap((a+i), (a + j));
  32.        }
  33.    }
  34. }
  35.  
  36. /* Main*/
  37. int main()
  38. {
  39.     char a[] = "abcd";
  40.     permute(a, 0, 3);
  41.     return 0;
  42. }

$ 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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.