string full permutation algorithmset R={R1,R2,..., rn} is the n element to be arranged, Ri=r-{ri}
Ri+perm (x) represents the arrangement of the prefix ri, preceded by each permutation of the fully arranged Perm (x).
(1) When N=1, Perm (r) = (R), where r is the only element in the set R.
(2) When n>1, Perm (R) can be composed of (R1) +perm (R1), (R2) +perm (R2),..., (RN) +perm (RN).
This algorithm is designed according to the above thought. It is easy to come up with the idea that this algorithm is easier to implement using recursion.
Set Perm (LIST,K,M) to recursively produce all permutations of all permutations where the prefix is list[0:k-1] and the suffix is list[k:m].
Then the call algorithm perm (LIST,0,N-1) produces the full array of list[0:n-1].
the implementation code for the algorithm is as follows:Note: Call Perm (S,0,strlen (s)-1) in the main () function
#include <iostream>using namespace Std;void Swap (char &s1,char &s2) {char temp=s1;s1=s2;s2=temp;} void Perm (char s[],int k,int m) {if (k==m) cout<<s<<endl;else{for (int i=k;i<=m;i++) {Swap (s[k],s[i]); Perm (S,K+1,M); Swap (S[k],s[i]);}} int main () {char s[]= "ABCD"; Perm (S,0,strlen (s)-1); return 0;}
Program Run Result:
Full alignment issues