Given an array, the task is to print or display all the permutations of this array using STL in C++.
Examples:
Input: a[] = {1, 2, 3}
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Input: a[] = {10, 20, 30, 40}
Output:
10 20 30 40
10 20 40 30
10 30 20 40
10 30 40 20
10 40 20 30
10 40 30 20
20 10 30 40
20 10 40 30
20 30 10 40
20 30 40 10
20 40 10 30
20 40 30 10
30 10 20 40
30 10 40 20
30 20 10 40
30 20 40 10
30 40 10 20
30 40 20 10
40 10 20 30
40 10 30 20
40 20 10 30
40 20 30 10
40 30 10 20
40 30 20 10
Approach: The next possible permutation of the array can be found using next_permutation() function provided in STL. Syntax:
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last);
Below is the implementation of the above Approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void display( int a[], int n)
{
for ( int i = 0; i < n; i++) {
cout << a[i] << " " ;
}
cout << endl;
}
void findPermutations( int a[], int n)
{
sort(a, a + n);
cout << "Possible permutations are:\n" ;
do {
display(a, n);
} while (next_permutation(a, a + n));
}
int main()
{
int a[] = { 10, 20, 30, 40 };
int n = sizeof (a) / sizeof (a[0]);
findPermutations(a, n);
return 0;
}
|
Output:Possible permutations are:
10 20 30 40
10 20 40 30
10 30 20 40
10 30 40 20
10 40 20 30
10 40 30 20
20 10 30 40
20 10 40 30
20 30 10 40
20 30 40 10
20 40 10 30
20 40 30 10
30 10 20 40
30 10 40 20
30 20 10 40
30 20 40 10
30 40 10 20
30 40 20 10
40 10 20 30
40 10 30 20
40 20 10 30
40 20 30 10
40 30 10 20
40 30 20 10
Time Complexity: O(N*N!) As, the next_permutation() function takes O(N) time to find the next permutation and there are N! number of permutations for an array of size N.
Auxiliary Space: O(1) As no auxiliary space is used.