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

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.