A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB

Here is a solution that is used as a basis in backtracking.

Write a program to print all permutations of a given stringC Programming

[pastacode lang=”c” manual=”%2F%2F%20C%20program%20to%20print%20all%20permutations%20with%20duplicates%20allowed%0A%23include%20%3Cstdio.h%3E%0A%23include%20%3Cstring.h%3E%0A%20%0A%2F*%20Function%20to%20swap%20values%20at%20two%20pointers%20*%2F%0Avoid%20swap(char%20*x%2C%20char%20*y)%0A%7B%0A%20%20%20%20char%20temp%3B%0A%20%20%20%20temp%20%3D%20*x%3B%0A%20%20%20%20*x%20%3D%20*y%3B%0A%20%20%20%20*y%20%3D%20temp%3B%0A%7D%0A%20%0A%2F*%20Function%20to%20print%20permutations%20of%20string%0A%20%20%20This%20function%20takes%20three%20parameters%3A%0A%20%20%201.%20String%0A%20%20%202.%20Starting%20index%20of%20the%20string%0A%20%20%203.%20Ending%20index%20of%20the%20string.%20*%2F%0Avoid%20permute(char%20*a%2C%20int%20l%2C%20int%20r)%0A%7B%0A%20%20%20int%20i%3B%0A%20%20%20if%20(l%20%3D%3D%20r)%0A%20%20%20%20%20printf(%22%25s%5Cn%22%2C%20a)%3B%0A%20%20%20else%0A%20%20%20%7B%0A%20%20%20%20%20%20%20for%20(i%20%3D%20l%3B%20i%20%3C%3D%20r%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20swap((a%2Bl)%2C%20(a%2Bi))%3B%0A%20%20%20%20%20%20%20%20%20%20permute(a%2C%20l%2B1%2C%20r)%3B%0A%20%20%20%20%20%20%20%20%20%20swap((a%2Bl)%2C%20(a%2Bi))%3B%20%2F%2Fbacktrack%0A%20%20%20%20%20%20%20%7D%0A%20%20%20%7D%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20functions%20*%2F%0Aint%20main()%0A%7B%0A%20%20%20%20char%20str%5B%5D%20%3D%20%22ABC%22%3B%0A%20%20%20%20int%20n%20%3D%20strlen(str)%3B%0A%20%20%20%20permute(str%2C%200%2C%20n-1)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C” highlight=”” provider=”manual”/]

Output:

ABC
ACB
BAC
BCA
CBA
CAB


Algorithm Paradigm:
Backtracking
Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a a permutation.

[ad type=”banner”]