A full permutation is list of all variation for given items (usually numbers). For example, the full permutation of 3 elements are:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Also Read: C program to find factorial of any number using recursion
Also Read: C++ program to enter a number and print it into words
As we can easily calculate, the total number of iterations is n! (factorial). How do we get this number? The most simple way is to think of the number of different items we can choose for each position. For example, for the first place, we have n choices, and we have n-1 choices for the second place, and etc. Thus we have n*(n-1)*(n-2)*…1 that gives a total number n!.
So how to emulate this for the whole process? First, we can define a recursive function that ends printing one solution by checking if we have reached the end. For each iteration, we can simply swap the current item with the rest of the items and try the next position recursive. As we use a global array variable nums to keep the items, we need to swap the items back after each recursion call. The source code is pretty straight forward. Open Visual Studio, choose the ‘Console Application’ from ‘C++’ language projects.
check if reach the end of iteration
0; j < n; j ++)
i; j < n; j ++)
nums[j]); // swap
i + 1); // recursive
nums[j]); // swap it back
declare a dynamic array
< n; i ++)
with numbers as 1, 2, 3, … n
Also Read: C++ Program to calculate roots of quadratic equation ax^2+bx+c=0
Also Read: C++ program to find sum of elements above and below the main digonal of a matrix
1 thought on “What is Recursive Permutation in C++? [Algorithm and Source Code]”
Hi, I'm sort of a beginner at programming. I've used VS2012, opened a new project for VC++ and select Console Application. Copy and paste the program and when I press F5, VS says me that there an error.
error C1033: cannot open program database ''
Could someone help me?