Javatpoint Logo
Javatpoint Logo

Q. Program to find all the permutations of a string.

To solve this problem, we need to understand the concept of backtracking.

According to the backtracking algorithm:

  • Fix a character in the first position and swap the rest of the character with the first character. Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with A, B and C respectively.
  • Repeat step 1 for the rest of the characters like fixing second character B and so on.
  • Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again, and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.
  • Repeat these steps for BAC and CBA, to get all the permutations.
Program to find all the permutations of a string

Algorithm

  1. Define a string.
  2. Fix a character and swap the rest of the characters.
  3. Call the generatePermutation() for rest of the characters.
  4. Backtrack and swap the characters again.

Solution

Python

Output:

All the permutations of the string are: 
ABC
ACB
BAC
BCA
CBA
CAB

C

Output:

All the permutations of the string are: 
ABC
ACB
BAC
BCA
CBA
CAB

JAVA

Output:

All the permutations of the string are: 
ABC
ACB
BAC
BCA
CBA
CAB

C#

Output:

All the permutations of the string are: 
ABC
ACB
BAC
BCA
CBA
CAB

PHP

Output:

All the permutations of the string are: 
ABC
ACB
BAC
BCA
CBA
CAB

Next TopicPrograms List




Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials