- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Printing all permutations of a given string is an example of backtracking problem. We will reduce the size of the substring to solve the sub-problems, then again backtrack to get another permutation from that section.
For an example, if the string is ABC, the all permutations will be ABC, ACB, BAC, BCA, CAB, CBA.
The complexity of this algorithm is O(n!). It is a huge complexity. When the string size increases, it takes a longer time to finish the task.
Input and Output
Input: A string “ABC” Output: All permutations of ABC is: ABC ACB BAC BCA CBA CAB
Algorithm
stringPermutation(str, left, right)
Input: The string and left and right index of characters.
Output: Print all permutations of the string.
Begin if left = right, then display str else for i := left to right, do swap str[left] and str[i] stringPermutation(str, left+1, right) swap str[left] and str[i] //for backtrack done End
Example
#include<iostream> using namespace std; void stringPermutation(string str, int left, int right) { if(left == right) cout << str << endl; else { for(int i = left; i<= right; i++) { swap(str[left], str[i]); stringPermutation(str, left + 1, right); swap(str[left], str[i]); //swap back for backtracking } } } int main() { string str = "ABC"; cout << "All permutations of " << str << " is: " <<endl<<endl; stringPermutation(str, 0, str.size()-1); }
Output
All permutations of ABC is: ABC ACB BAC BCA CBA CAB
- Related Articles
- Python Program to print all permutations of a given string
- C Program to print all permutations of a given string
- Print all distinct permutations of a given string with duplicates in C++
- Print all permutations of a string in Java
- Print all palindrome permutations of a string in C++
- Print all the palindromic permutations of given string in alphabetic order in C++
- How to find all possible permutations of a given string in Python?
- Python Program to Print All Permutations of a String in Lexicographic Order without Recursion
- Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
- All permutations of a string using iteration?
- Java Program to print distinct permutations of a string
- C++ Permutations of a Given String Using STL
- Print all permutations with repetition of characters in C++
- Program to print all substrings of a given string in C++
- Creating all possible unique permutations of a string in JavaScript

Advertisements