Gives a collection of n (n>=1) elements, outputting all possible permutations of the collection.
The number of 3!=6, such as the full array of ABC
For: ABC, the BC full arrangement starting with ACB a
BAC, the AC full arrangement at the beginning of BCA b
CBA, CAB C begins with a full array of BA
The clue to recursion is followed by ... The permutation of n elements can be transformed into permutation problems of n-1 elements.
The code is as follows:
1 /*2 recursion is performed from the back, and the results go backwards from back3 ABCD has a full arrangement of 1 times4 a BCD's full arrangement A and a change position after conversion to find the full array of BCD after the arrangement need to change back to ensure that the initial string is unchanged5 b ACD's full arrangement A and B change position after conversion to the whole arrangement of the ACD after the arrangement need to change back to ensure that the initial string is unchanged6 c Bad's full arrangement A and C change position after conversion to the full permutation of the order to find out after the arrangement need to change back to ensure that the initial string unchanged7 d BCA of the full arrangement of a and D after the change of position to find the full alignment of the BCA after the arrangement need to change back to ensure that the initial string is unchanged8 End Condition: When the last letter is left, his whole arrangement is himself.9 */Ten One#include <stdio.h> A #defineSWAP (X,y,t) ((t=x), (x) = (y), (y) = (t)) - voidPermChar*list,intIintN); - intMain () the { - Chara[5]="ABCD"; -Perm (A,0,3); -printf"%s", a); + return 0; - } + A voidPermChar*list,intIintN) at { - intj,temp; - if(i = = N) {//recursive end When I is the last element - for(j =0; J <= N; J + + ) -printf"%c", List[j]); -printf"\ n —————— \ n"); in } - Else{ to for(j = i; J <= N; j + +) {//the full arrangement of I to n +SWAP (list[i],list[j],temp);//with each element as the beginning of the full arrangement -Perm (list,i+1, n);//ask for the i+1 to N's full arrangement theSWAP (list[i],list[j],temp);//ensure that the initial array is unchanged * } $ }Panax Notoginseng } - the +
Full sort recursive algorithm