Permutations (STL)

Print all the permutations of the input string using STL functions.

Example

Input string : “ABC”

Output : ABC, ACB, BAC, BCA, CAB, CBA

Time complexity : O(n)

Algorithm

Here we use next_permute() function, which rearranges the given string and return lexicographically next permutation.

a. We store the sorted string.

b. Until the function next_permutation() return false.

c. Print all permutations.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
void permutations(string str)
{
    sort(str.begin(), str.end());//Sort input string
    cout<<str<<endl;
    while (next_permutation(str.begin(), str.end()))
    {
        cout<<str<<endl;
    }  
}
//Main functions
int main()
{
    string str = "CBA";
    permutations(str);
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top