The last section of the algorithm class refers to the full array of generation problems, today I found some information on the Internet, summed up a few ways:
A. Recursive collation algorithm.
Two. Dictionary ordering method.
Three. Increment the carry numeral method.
Four. Descending carry numeral method.
Five. Adjacent position Exchange method.
Six. N binary method.
Here's a look at some of these algorithms.
A. Recursive collation algorithm.
Recursive collation algorithm is relatively concise, the implementation of a variety of methods.
1. Recursive algorithm (non-dictionary order)
1#include <iostream>2#include <algorithm>3 4 5 using namespacestd;6 intsum=0;7 inta[Ten];8 intN;9 //consider the full arrangement of [l,n-1] intervalsTen voidPerm (intl) One { A //output, total number of permutations plus one - if(l==n-1) - { the for(intI=0; i<n;i++) - { -printf"%d", A[i]); - } +printf"\ n"); -sum++; + } A Else at { - //consider the arrangement of [l+1,n-1] -Perm (L +1); - for(inti=l+1; i<n;i++) - { - //The current bit (l) is exchanged separately from each subsequent bit (l+i). in swap (a[l],a[i]); - //The current bit (l) has been determined, now consider the [l+1,n-1] arrangement. toPerm (L +1); + //Restore - swap (a[l],a[i]); the } * } $ }Panax Notoginseng intMain () - { theFreopen ("Data.out","W", stdout); +scanf"%d",&n); A for(intI=0; i<n;i++) the { +a[i]=i+1; - } $Perm (0); $printf"A total of%d permutations. \ n", sum); - return 0; -}View Code
2. Backtracking method.
Two. Dictionary ordering method.
1#include <iostream>2#include <algorithm>3 4 using namespacestd;5 intN;6 Const intmaxn=1e2+Ten;7 intA[MAXN];8 Const intinf=0x3f3f3f;9 BOOLnext_perm ()Ten { One intk=-1; A //for (int i=0;i<n-1;i++) - // { - //if (a[i]<a[i+1]) the // { - //k=i; - // } - // } + //from right to left to meet a[i]<a[i+1] The most right I, arranged from this position began to change - for(inti=n-2; i>=0; i--) + { A if(a[i]<a[i+1]) at { -k=i; - Break; - } - } - //indicates that this is already the largest dictionary order. in if(k==-1) - { to return false; + } - //next find the smallest value larger than a[k in [k+1,n-1], so that it is the smallest permutation of the ordered dictionary the intans=INF; * intindex=0; $ for(inti=k+1; i<n;i++)Panax Notoginseng { - if(a[i]>A[k]) the { + if(a[i]<ans) A { theindex=i; +ans=A[i]; - } $ } $ } - swap (A[k],a[index]); - //next the number of [k+1,n-1] is inverted the intI=1; - while(1)Wuyi { the if(k+i>=n-i) - { Wu Break; - } AboutSwap (a[k+i],a[n-i]); $i++; - } - return true; - } A intMain () + { thescanf"%d",&n); - for(intI=0; i<n;i++) $ { thescanf"%d",&a[i]); the } the next_perm (); the for(intI=0; i<n;i++) - { inprintf"%d", A[i]); the } theprintf"\ n"); About return 0; the}View Code
"Algorithm series learning One" full-array generation algorithm