In order to solve this problem, we need to understand the concept of backtracking.
According to the backtracking algorithm:
- Fix the character in the first position, and then replace the remaining characters with the first character. As in ABC, in the first iteration, three strings are formed by swapping A with A, B and C, respectively: ABC, BAC, and CBA.
- Repeat step 1 for the remaining characters, for example, fix the second character B, and so on.
- Now swap again to return to the previous position. For example, from ABC, we form ABC by fixing B again, then backtracking to the previous position and swapping B with C. Therefore, now we have ABC and ACB.
- Repeat these steps for BAC and CBA to obtain all permutations.
algorithm
- Define a string.
- Fix the roles and swap the remaining roles.
- Call generatePermutation() for the remaining characters.
- Backtrack and swap characters again.
solution
package Permutations;
public class PermuteString {
// Function for generating different permutations of the string
public static void generatePermutation(String str, int start, int end) {
// Prints the permutations
if (start == end - 1)
System.out.println(str);
else {
for (int i = start; i < end; i++) {
// Swapping the string by fixing a character
str = swapString(str, start, i);
// Recursively calling function generatePermutation() for rest of the characters
generatePermutation(str, start + 1, end);
// Backtracking and swapping the characters again.
str = swapString(str, start, i);
}
}
}
// Function for swapping the characters at position I with character at position
// j
public static String swapString(String a, int i, int j) {
char[] b = a.toCharArray();
char ch;
ch = b[i];
b[i] = b[j];
b[j] = ch;
return String.valueOf(b);
}
public static void main(String[] args) {
String str = "ABC";
int len = str.length();
System.out.println("All the permutations of the string are: ");
generatePermutation(str, 0, len);
}
}