Enter a string that contains different characters. The program outputs all permutations (all permutations) of the string.
voidFChar*STR,intLenintN) { inti; Chartmp; Char*p = (Char*)malloc(len+1); if(n==len-1) {printf ("%s\n", str); }Else{ for(i=n;i<len;i++) {strcpy (P,STR); TMP= * (str+N); * (str+n) = * (str+i); * (str+i) =tmp; F (Str,len,n+1); strcpy (STR,P); } } Free(P); } intMainintargcChar**argv) { CharStr[] ="XYZ"; F (str,3,0); printf ("\ n"); return 0; }
For example: Given the string "XYZ", the program outputs:
Xyz
Xzy
Yxz
zz[
yy[
Zxy
Also enter a string, where you can include a repeating string, and the output is fully arranged.
#include <stdio.h>#include<string.h>#include<memory.h>intM//Record string lengthintN//the number of character types in the record stringCharmap[ the];//What kinds of characters are recordedintcount[ the];//record how many of each character voidMake_map (Char*STR)//information about the statistics string{ ints[ the]; inti; memset (s),0,sizeof(s)); memset (Count,0,sizeof(count)); M=strlen (str); while(*str) {s[*str]++; STR++; } N=0; for(i=0;i< the; i++) if(S[i]) {Map[n]=i; Count[n]=S[i]; N++; } } intstack[ +];//recursively uses stacks, and records the current generated permutations voidFind (intDepth//recursive backtracking for full-array generation{ intk=0; if(depth==m) {inti; for(i=0; i<depth;i++) {Putchar (map[stack[i]); //printf ("%d\n", k);} putchar ('\ n'); } Else { inti; for(i=0; i<n;i++) if(Count[i]) {stack[depth]=i; Count[i]--; Find (Depth+1); Count[i]++; } } } intMain () {Charstr[ +]; Gets (str); Make_map (str); Find (0); return 0;}
Note: If you encounter a,s[*str]++ representing s[65]++, you encounter B, then s[' B ']++
Finally, s[' A '],s[' B '],s[' C ' ... The value is a, B 、...... The number of occurrences of these letters
Two methods for the full array of strings