Users Online

· Guests Online: 100

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Print All Permutations using BackTracking

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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.74 seconds
10,832,607 unique visits