C Program to print all permutations of a given string

In this problem, we are given a string. Our task is to create a c program to print all permutations of a given string.

This program will find all possible combinations of the given string and print them.

Permutation is the arrangement of all parts of an object, in all possible orders of arrangement.

Let’s take an example to understand the problem,

Input

xyz

Output

xyz, xzy, yxz, yzx, zxy, zyx

Explanation

These are all permutations take in order.

To solve this problem, we will use backtracking i.e. taking each character of the string as the first character of the permutation and then sequentially choosing all remaining characters of the string one by one. And thus, printing all the permutations of the string.

Program to print all permutations of a given string

//Program to print all permutations of a given string −

Example

Live Demo

#include <iostream>
using namespace std;
void findPermutations(string str, int l, int r){
if (l == r)
cout<<str<<" ";
else{
for (int i = l; i <= r; i++){
swap(str[l], str[i]);
findPermutations(str, l+1, r);
swap(str[l], str[i]);
}
}
}
int main(){
string str = "WXYZ";
int n = str.size();
findPermutations(str, 0, n-1);
return 0;
}

Output

WXYZ WXZY WYXZ WYZX WZYX WZXY XWYZ XWZY XYWZ XYZW XZYW XZWY YXWZ YXZW YWXZ
YWZX YZWX YZXW ZXYW ZXWY ZYXW ZYWX ZWYX ZWXY

Updated on: 17-Jul-2020

973 Views