您可以动态分配一个数组,该数组将保存代表每个排列的单个 char 数组(或 C 字符串)。使此代码通用的一件事是在 main() 中为给定字符串找到 total_permutations 的值 strlen N,实际上是阶乘 (N)。这里:
void swap(char* A, char* B) {
char t;
t = *A;
*A = *B;
*B = t;
}
int permute(char **arr_of_chars, int count, char *a, int i, int n)
{
int k=0;
char *b[100];
int j;
if (i == n) {
// *b[k]=a;
printf("%s\n", a);
memcpy(arr_of_chars[count], a, strlen(a));
count++;
i++;
} else {
for (j = i; j <= n; j++) {
swap((a+i), (a+j));
count = permute(arr_of_chars, count, a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
return count;
}
int main() {
char str[] = "";
char **arr_of_str = NULL;
int len_str = strlen(str);
int i = len_str;
int total_permutations = 1;
while (i > 0) { /* Get all the combinations */
total_permutations *= i;
i--;
}
arr_of_str = (char **) malloc(total_permutations * sizeof(char*));
for (i=0; i <total_permutations; i++) {
arr_of_str[i] = (char *) malloc(sizeof(char) * len_str);
}
permute(arr_of_str, 0, str, 0, (len_str-1));
for (i=0; i <total_permutations; i++) {
printf("%s \n", arr_of_str[i]);
free(arr_of_str[i]);
}
free(arr_of_str);
}