Title: Enter a string to print out all the permutations of the characters in the string.
For example, if you enter the string ABC, all strings that can be arranged by the character A,b,c are printed: ABC,ABC,BAC,BCA,CAB,CBA
We can look at the entire string arrangement as two steps: first to find all the characters that may appear in the first position, that is, to exchange the first character and all subsequent characters. is to switch between the first character a and the b,c in the back of the scene. The second step is to fix the first character, to arrange for all subsequent characters. At this point we are still dividing all the characters in the back into two parts: the first character of the following character, and all the characters after the character. Then exchange the first character with the character after it ...
Note: (a) divides the string into two parts, one for the first character of the string and one for all characters after the first character. Next we ask for the arrangement of the strings in the shaded section. (b) Swap the first character with the character after it.
Analysis here, we can see that this is actually a very typical recursive thinking, so we write the following Java code:
/** * Enter a string to print out all the permutations of the string. * For example, enter the string ABC, print out all the strings that can be arranged by the character A,b,c ABC,ACB,BAC,BCA,CAB,CBA */package swordforoffer;/** * @author Jinshuangqi * * August 7, 2015 */public class E28stringpermutation {public void swap (char[] arr,int idx1,int idx2) {Char temp = Arr[idx1];arr[id X1] = arr[idx2];arr[idx2] = temp;} public void permutation (char[] arr,int index,int size) {if (index = = size) {for (int i = 0;i<arr.length;i++) { System.out.print (arr[i]+ "");} System.out.println ();} else{for (int i = index;i<size;i++) {if (I!=index && arr[i] = = Arr[index]) continue;swap (Arr,i,index); Permutation (arr,index+1,size); swap (Arr,i,index);}} public static void Main (string[] args) {String str= "ABCD"; char[] CHS = Str.tochararray (); E28stringpermutation test = new E28stringpermutation (); test.permutation (chs,0,4);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Sword refers to the offer surface question (Java Edition): string arrangement