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: A string “ABC” Output: All permutations of ABC is: ABC ACB BAC BCA CBA CAB
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
#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); }
All permutations of ABC is: ABC ACB BAC BCA CBA CAB