1+ /*
2+ Backtracking algorithm used in the program:-
3+
4+ >>Fix a character in the first position and swap the rest of the character with the first character.
5+ Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with
6+ A, B and C respectively.
7+ >>Repeat step 1 for the rest of the characters like fixing second character B and so on.
8+ >>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again,
9+ and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.
10+ >>Repeat these steps for BAC and CBA, to get all the permutations.
11+ */
12+ public class PermuteString {
13+ //Function for swapping the characters at position I with character at position j
14+ public static String swapString (String a , int i , int j ) {
15+ char [] b =a .toCharArray ();
16+ char ch ;
17+ ch = b [i ];
18+ b [i ] = b [j ];
19+ b [j ] = ch ;
20+ return String .valueOf (b );
21+ }
22+
23+ public static void main (String [] args )
24+ {
25+ String str = "ABC" ;
26+ int len = str .length ();
27+ System .out .println ("All the permutations of the string are: " );
28+ generatePermutation (str , 0 , len );
29+ }
30+
31+ //Function for generating different permutations of the string
32+ public static void generatePermutation (String str , int start , int end )
33+ {
34+ //Prints the permutations
35+ if (start == end -1 )
36+ System .out .println (str );
37+ else
38+ {
39+ for (int i = start ; i < end ; i ++)
40+ {
41+ //Swapping the string by fixing a character
42+ str = swapString (str ,start ,i );
43+ //Recursively calling function generatePermutation() for rest of the characters
44+ generatePermutation (str ,start +1 ,end );
45+ //Backtracking and swapping the characters again.
46+ str = swapString (str ,start ,i );
47+ }
48+ }
49+ }
50+ }
0 commit comments