Permutations of a given string using STL
Last Updated :
11 Jul, 2022
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword
Below are the permutations of string ABC.
“ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”
We have discussed C implementation to print all permutations of a given string using backtracking here. In this post, C++ implementation using STL is discussed.
Method 1 (Using rotate())
std::rotate function rotates elements of a vector/string such that the passed middle element becomes first. For example, if we call rotate for “ABCD” with middle as second element, the string becomes “BCDA” and if we again call rotate with middle as second element, the string becomes “CDAB”. Refer this for a sample program.
Below is C++ implementation.
C++
#include <bits/stdc++.h>
using namespace std;
void permute(string str, string out)
{
if (str.size() == 0)
{
cout << out << endl;
return ;
}
for ( int i = 0; i < str.size(); i++)
{
permute(str.substr(1), out + str[0]);
rotate(str.begin(), str.begin() + 1, str.end());
}
}
int main()
{
string str = "ABC" ;
permute(str, "" );
return 0;
}
|
Output
ABC
ACB
BCA
BAC
CAB
CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
Method 2 (using next_permutation)
We can use next_permutation that modifies a string so that it stores lexicographically next permutation. If current string is lexicographically largest, i.e., “CBA”, then next_permutation returns false.
We first sort the string, so that it is converted to lexicographically smallest permutation. Then we one by one call next_permutation until it returns false.
C++
#include <bits/stdc++.h>
using namespace std;
void permute(string str)
{
sort(str.begin(), str.end());
do {
cout << str << endl;
} while (next_permutation(str.begin(), str.end()));
}
int main()
{
string str = "CBA" ;
permute(str);
return 0;
}
|
Output
ABC
ACB
BAC
BCA
CAB
CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(1)
Note that the second method always prints permutations in lexicographically sorted order irrespective of input string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...