The full arrangement of the 1~n
(1) Idea: According to the idea of recursion, initializing the set S contains all elements of 1~n. If the 1~n set S is empty, then the output is fully arranged, otherwise each element i is considered from small to large, and after I is added at the end of a, the set S becomes S-{i}. Here we do not need to assemble s, just use a variable cur to represent the number of the current bit to fill. Then the elements that are not present in a can be selected.
#define N 100int a[n];void print_permutation (int n, int*a, int cur) {if (cur = = N) {for (int i = 0; i < N; i++) printf ("%d ", A[i]);p rintf (" \ n ");} else for (int i = 1; I <= n; i++) {int ok = 1;for (int j = 0; J < cur;j++) if (a[j] = = i) {ok = 0; if (OK) {A[cur] = i;print_permutation (n, A, cur + 1);}}}
Permutation of a reconfigurable set
If you change the above question to "input array p, output all permutations of elements in the dictionary order," Note that the elements in the P array can be duplicated. Then the method is broadly similar to the full arrangement, but some details need to be changed:
(1) First to order the P array, and then call the Print_permutation function;
(2) because the elements in the P array can be repeated, so to check the cur bit before there are several elements p[i], false with C1, and the P array has a total of C2, then you can choose at this time;
(3) Since elements in the P array can recur, the enumeration should not be repeated, so the first element of P and all elements that are not the same as the previous element are also checked.
#define N 100int a[n];int p[n];void print_permutation (int N, int*p, int*a, int cur) {if (cur = = N) {for (int i = 0; i < n ; i++) printf ("%d", A[i]);p rintf ("\ n");} else for (int i = 0; i < n; i++)//Enumerate each position if (!i | | P[i]! = P[i-1])//Note elements cannot be repeated enum {int C1 = 0, C2 = 0;for (int j = 0; j < cur; j + +) if (a[j] = = P[i]) c1++;for (int j = 0; J < ; N J + +) if (p[j] = = P[i]) c2++;if (C1<C2) {a[cur] = P[i];p rint_permutation (n, P, A, cur + 1);}}
Violent Search Topic Summary: Full permutation and clustering algorithm