Java implementation of a fully-arranged Algorithm
Full sorting is a common problem and a favorite question during the interview. Here we introduce a Java implementation method.
I. Ask questions
The so-called Full arrangement is to list all possible arrangements for a given set of numbers or letters, such as {a, B, c }.
(A B c) (a c B) (B a c) (B c a) (c a B) (c B)
That is, the factorial arrangement of N.
Ii. Problem Analysis
For complex problems, you can start with a simple one. Consider the extreme situations first,
1) For example, if only {A} exists, there is only one full arrangement.
2) by extension, {A B} can be arranged in two full ways (a B) (B a), which can be seen as traversing {A B} one by one to retrieve the first one, there is only one arrangement for the remaining one.
3) Similarly, there are 6 full arrangements for {a B c}. As mentioned above, we can think of them as extracting A, B, and C one by one, and then fully arranging the remaining two, use 2.
Obviously, this is a recursive algorithm.
Iii. Problem Solving
So how to implement this recursive algorithm. In general, assume there is a group of numbers P = {x1, x2,... xn}. According to the above analysis,
Perm (p) = x1 perm (P1) + x2 perm (P2) +... XN perm (PN) (Formula 1)
Where p1 = P-X1, Pn = p-XN.
Similarly, P1. .. PN is also calculated according to formula 1 until P is 1.
In Java, you can use list to identify P, traverse the elements in P one by one, and get one at a time, that is, remove this element from P, the rest will be traversed one by one based on this algorithm until P is 1. The removed element is stored in a temporary list. When P is set to 1, it is OK to list the elements in the remove list and the unique elements in P.
The Java implementation code is as follows:
Import java. util. arraylist;
Import java. util. List;
Public class permutation {
Private Static list <integer> List = new arraylist <integer> ();
Private Static int total;
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
List. Add (1 );
List. Add (2 );
List. Add (3 );
List. Add (4 );
List. Add (5 );
Perm (list, new arraylist <integer> ());
System. Out. println ("Total:" + total );
}
Private Static void perm (list <integer> list, list <integer> removed ){
Int length = List. Size ();
If (length = 1 ){
For (INT value: removed ){
System. Out. Print (Value + "");
}
System. Out. println (list. Get (0 ));
Total ++;
} Else {
For (INT I = 0; I <length; I ++ ){
List <integer> temp = new arraylist <integer> ();
Temp. addall (list );
Temp. Remove (I );
List <integer> holder = new arraylist <integer> ();
Holder. addall (removed );
Holder. Add (list. Get (I ));
Perm (temp, holder );
}
}
}
}