This post will find all permutations of a string containing all distinct characters in C++.

For example, the string ABC has 6 permutations, i.e., ABC, ACB, BAC, BCA, CBA, CAB.

Practice this problem

Approach 1: (Using Backtracking)

We can in-place find all permutations of the given string by using backtracking. The idea is to swap each of the remaining characters in the string with its first character and then find all the permutations of the remaining characters using a recursive call. The base case of the recursion is when the string is left with only one unprocessed element. Following is the recursion tree for printing all permutations of the string ABC:

Permutations of a string

Download  Run Code

Output:

ABC
ACB
BAC
BCA
CBA
CAB

Approach 2: (Using STL)

We can use std::rotate to in-place rotate a string in linear time and recursively permute on the rotated string. Following is the recursion tree for printing all permutations of the string ABC:

Permutations of a string using STL

Download  Run Code

Output:

ABC
ACB
BCA
BAC
CAB
CBA

 
The time complexity of the above solutions is O(n.n!) as there are n! permutations for a string of length n, and each permutation takes O(n) time.

 
Note that the above solution doesn’t handle strings containing duplicate characters. We have discussed how to handle duplicate characters here.

 
Also see:

Iterative approach to finding permutations of a string – C++, Java, and Python

Find all lexicographic permutations of a string

Find all palindromic permutations of a string