The full arrangement refers to the number of n (or other characters) of all possible permutations, such as 1 2 33 digits of the full arrangement is
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
So the question comes, arbitrarily enter a number greater than 1 N, listing the full array of 1-n n numbers.
If you try to enumerate the full permutations of 1 2 3 manually, you will find that we usually make the rules in our minds and enumerate them according to the established rules to get all the permutations.
The rules we set here are:
(Imagine we've got 3 numbers in our hands, with a, B, C, three seats on the ground)
1) before each vacancy, try to put down a number in the order of 1->2->3, and if the number is already down, try the next
2) Move one cell backwards after each drop and repeat the 1->2->3 attempt
3) If there is no new possibility in the current position, retrieve the current position number and move left one cell to try again
According to the above rules it is easy to deduce that the first permutation is 1 2 3
Retrieve 3, return B position, fetch 2, and then press 1->2->3 try, find can put down 3, move right to C, try to drop 2, get 1 3 2
The next step must return to the position of a new possibility, at this time has retrieved all the numbers, according to the rule down 2, move to B, put down 1, move to C, put down 3, get 2 1 3
。。。
Here's what the implementation code looks for:
[Java]View PlainCopyprint?
- Public class Permutation {
- private int max;
- private int[] array;
- private int[] hold;
- Public permutation (int max) {
- This.max = max;
- Array = new Int[max + 1];
- Hold = new Int[max + 1];
- }
- public void permute (int step) {
- if (step = = max + 1) {
- For (int i = 1; I <= max; i++) {
- System.out.print (Array[i] + "");
- }
- System.out.println ();
- return; //returns to the last step, which is the last row of the most recent call to the Permute method
- }
- //try in order of 1->2->3->...->n
- For (int num = 1; num <= max; num++) {
- //Determine if the number is still held
- if (hold[num] = = 0) {
- Array[step] = num;
- Hold[num] = 1;
- //recursion: Move right one cell repeat the attempt to traverse the number
- Permute (step + 1);
- Retrieve current position number when returning to current position
- Hold[num] = 0;
- }
- }
- }
- public static void Main (string[] args) {
- Permutation FA = new permutation (3);
- Fa.permute (1);
- }
- }
Run output
[Java]View PlainCopy print?
- 1 2 3
- 1 3 2
- 2 1 3
- 2 3 1
- 3 1 2
- 3 2 1
We use a pseudo-sequence diagram to help understand the execution of recursive calls
By the way, there are many algorithms for the full permutation problem, and the model of the depth-first algorithm is used in this paper.
Java and Algorithm (4)-Digital full array