1 Public classA {2 Static intK=0;3 Public Static voidMain (String args[]) {4 Char[] ss = {' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ',5' 5 ', ' 6 ', ' 7 ' };6Permutation (SS, 0);7 }8 Public Static voidPermutation (Char[] SS,inti) {9 Ten if(ss = =NULL|| I < 0 | | i >ss.length) { One return; A } - if(i = =ss.length) { -String A =NewString (ss); the System.out.println (a); -k++; - if(k==4) -System.exit (0); +}Else { - for(intj = i; J < Ss.length; J + +) { + Chartemp = Ss[j];//swaps the prefix so that it produces the next prefix ASS[J] =Ss[i]; atSs[i] =temp; -Permutation (ss, I + 1); -temp = Ss[j];//swap the prefixes back to continue with the previous prefix arrangement. -SS[J] =Ss[i]; -Ss[i] =temp; - } in } - } to}
This recursive execution results in many, many, results of 14!. The first four results are:
12345671234567
12345671234576
12345671234657
12345671234675
Here's an analysis of the process:
So let's say:
Permutation (ss, 0);//Initial call, I value equals 3
In order to be convenient to say, the next call permutation function, I value equals a few, called the number of recursion
Permutation (ss, 0);//0 recursive start execution judgment if condition statement is not established
Run the For loop in the Else statement, J=0,I<14,//ss.length=14
Call permutation (ss, 0+1);
Permutation (ss, 0+1););//1 recursive start execution judgment if condition statement is not established
Run the For loop in the Else statement, J=1,J<14,//ss.length=14
Call Permutation (ss, +);
...
Permutation (ss, 13+1););//14 recursive start execution judgment if condition statement established
Executive System.out.println (a); a=12345671234567
After the recursion of number 14th is not established, return to the 13th recursive for loop for j + + processing,
Run for Loop, j=14,j<14, not set
After the recursion of number 13th is not established, return to the 12th recursive for loop for j + + processing,
Run for Loop, j=13,j<14, set up. Perform
Char temp = ss[13];//interchange prefix to produce the next prefix
SS[13] = ss[13];
SS[13] = temp;
Permutation (SS, 13 + 1);
Recursive explanation (II.)