voidpermute(int *list, int begin, int size); // 实现全排列的函数 voidswap(int *a, int *b); // 交换数组中两个数的值
int num = 0; // 记录全排列的次数
intmain() { int n; int *list; printf("Input the size of the number list: "); scanf("%d", &n); list = (int*)calloc(n, sizeof(int)); // 动态数组 // 初始化 printf("Input the number list:\n"); for (int i = 0; i < n; i++) { scanf("%d", &list[i]); }
permute(list, 0, n);
printf("The total number of permutation is %d", num); free(list); // 释放 }
voidpermute(int *list, int begin, int size) { if (begin >= size) { // a permutation is found num++; for (int i = 0; i < size; i++) { printf("%d ", list[i]); } printf("\n"); return; } for (int k = begin; k < size; k++) { if (k != begin) swap(&list[begin], &list[k]); permute(list, begin+1, size); if (k != begin) swap(&list[begin], &list[k]); } }
voidswap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }