
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Permutations of a Given String in C
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
#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
Advertisements