題目:
輸入一個字符串,打印該字符串中字符的全部排列。例如輸入字符串abc,則打印出由字符a、b、c所能排列出來的全部字符串abc、acb、bac、bca、cab和cba。code
#include <stdio.h> #include <string.h> void my_swap(char *p, char *q) { char tmp; tmp = *p; *p = *q; *q = tmp; } char cha[] = {'a', 'b', 'c', 'd', '\0'}; char chb[] = {'a', 'b', 'c', 'd','\0'}; void pf(char* a, char* p, int n) { if(n <= 0) return; if(n == 1) { printf("%s\n", a); return; } else { for(int i = 0; i < n; ++i) { my_swap(&p[0], &p[i]); pf(a, p+1, n-1); my_swap(&p[0], &p[i]); } } } int main(void) { char a2[3] = {'a', 'b', '\0'}; // pf(a2, a2, 2); pf(cha, cha, strlen(cha)); return 0; }