69267230
What is the whole arrangement "
Any element of M (m≤n) from n different elements, arranged in a certain order, is called an arrangement of extracting m elements from n different elements. All permutations are called when m=n. With the 123来 example, 123 of the full array has 123, 132, 213, 231, 312, 321 of these six.
Topic
A recursive algorithm is designed to generate a full array of n elements {r1,r2,..., rn}.
"Algorithmic explanation"
Set R={R1,R2,..., rn} is the n element to be arranged, Ri=r-{ri}.
The full array of elements in collection X is recorded as perm (x).
(RI) perm (x) represents the arrangement of the prefixes obtained before each permutation of the perm (x) in full arrangement.
The full arrangement of R can be summarized as follows:
When N=1, perm (r) = (R), where r is the only element in the set R;
When N>1, Perm (R) is composed of (R1) Perm (R1), (R2) Perm (R2), ..., (RN) perm (RN).
Realization idea: The whole group of numbers in the number of the first exchange of all the numbers, so it is always processed after the n-1 number of the full array.
Example
When n=3, and E={a,b,c}, then:
Perm (E) =a.perm ({b,c}) + B.perm ({a,c}) + C.perm ({A, b})
Perm ({b,c}) =b.perm (c) + c.perm (b)
A.perm ({b,c}) =ab.perm (c) + ac.perm (b) =AB.C + ac.b= (ABC, ACB)
"Recursive implementation"
123 of the full array of 123, 132, 213, 231, 312, 321 of these six. first of all, consider how 123, 213, and 321 of the three numbers are derived, 1 and self, 2, 3 Exchange obtained; then consider how 123 and 132, 213, 231, 312, and 321 are derived, the first number is unchanged, the second number and every three number exchange is obtained. Once this rule is found, the recursive code is easily written out.
"C + + code implementation"
- #include<iostream>
- #include<algorithm>
- Using namespace std;
- template<class type>
- void Perm (Type list[], int k, int m)
- { //produce all permutations of [list[k:m]
- if (k = = m)
- { //Only one element left
- For (int i = 0; i <= m; i++)
- cout << list[i];
- cout << Endl;
- }
- else //multiple elements to be arranged, recursively producing permutations
- For (int i = k; I <= m; i++)
- {
- Swap (list[k], list[i]);
- Perm (list, K + 1, m);
- Swap (list[k], list[i]);
- }
- }
- int main()
- {
- Char s[] = "ABCD";
- Perm (S, 0, 3);
- System ("pause");
- return 0;
- }
Recursive implementation algorithm of full permutation (Perm)