The second algorithm is my pen test encountered, then did not make out, on the internet to see other people write algorithms, feel too subtle, here to share.
Full arrangement
The so-called full arrangement is to print out all the permutations of all the characters in the string. For example abc , if you enter a string, print out all strings,,,, and, that can be arranged by a, B, abc and C acb bac bca cab cba .
#include <stdio.h> #include <string.h>static int number=0;void Swap (char *a, char *b) {Char temp = *a;*a = *b;*b = temp;} void Allrange (char* str,int start,int length) {if (start = = length-1) {printf ("%s\n", str); number++;} else{for (int i=start;i<=length-1;i++) {Swap (&str[start],&str[i]); Allrange (str,start+1,length); Swap (&str[start],&str[i]); }}}void permutation (char* str) {if (str = = NULL) return; Allrange (Str,0,strlen (str));} void Main () {char str[] = "ABCDE"; Permutation (str);p rintf ("number=%d\n", number);}
all combinations
What if you're not asking for all the permutations of a character, but for all combinations of characters? Or enter three characters A, B, C, then they have a combination a b c ab ac bc abc . Of course, we can learn from the whole arrangement of ideas, using the idea of decomposition of the problem, the end of the recursive solution. But here's a clever idea-based on bitmaps.
Assuming that the original element is n, the result of the final combination is 2 n ? 1 A. We can use the bitwise operation method: Assuming that the element originally has: A,b,c three, then 1 means take the element, 0 means no fetch. So takeais the001Takeabis the011。 So there are altogether three bits, each of which has two choices of 0 and 1. and000There's no point, so it's 2 n ? 1 a result.
The bitmap values for these results are ... 2^n-1. So from the value 1 to the value 2 n ? 1 Output results in turn:
001,,,,, 010 011 100 101 110 , 111 . The corresponding output combination results are:,,,,, a b ab c ac bc , abc .
So you can loop the 1~2^n-1 and then output a combination of the corresponding representatives. The code is as follows:
#include <stdio.h> #include <string.h>static int number=0;void combination (char *str) {if (str = = NULL) return ; int len = strlen (str); int n = 1<<len;printf ("n=%d\n", N); for (int i=1;i<n;i++) //from 1 to 2^len-1{for (int j=0; j<len;j++) {int temp = i;if (temp & (1<<J))
Invert stringMain.c
#include <stdio.h> #include <string.h>void print (char *str) { if (*str!= ') print (str+1); if (*str!= ') printf ("%c", *str);} int main (int argc,char **argv) {char *buff= "Hello World";p rint (Buff);p rintf ("\ n"); return 0;}
Combination algorithm of string permutation