赞
踩
本题为某厂机试题(本人亲历,未答出T_T),
本文涉及到的代码重点参考:https://blog.csdn.net/umbrellalalalala/article/details/79792451
**全排列**
枚举法,C的具体实现——通过迭代的方式,循环调用。
需要细细品,思路还得再理理,晚些时候有新的理解再写。直接贴代码:
#include <stdio.h> #include <stdlib.h> int cur = 0; long int j = 0; #define MAX 9 int a[MAX] = {0}; //#define MAX_CNT 9*8*7*6*5*4*3*2*1 //char array[MAX_CNT*9]; void list_all_array(int n, char *full_array, int cur) { if(cur == n) { //printf("arrar addr is 0x%x\n", full_array); for(int i = 0; i < n; i++) { sprintf(full_array + j + i, "%d", a[i]); printf("%c", full_array[j+i]); } j += n; printf("\n"); } else { for(int i = 1; i <= n; i++) { int ok = 1; for(int k = 0 ; k < cur; k++) if(a[k] == i) { ok = 0; break; } if(ok) { a[cur] = i; //printf("\t%s : j = %d\n\n", __func__, j); list_all_array(n, full_array, cur+1); } } } } int main() { int n = 0; long int k = 0; long int k_value = 1; int i = 0; retry1: printf("input n :"); scanf("%d", &n); if(n < 1 || n > 9) { printf("please retry!\n"); goto retry1; } for(i = n; i > 0; i--) { k_value *= i; } printf("%d! is %ld\n", n, k_value); retry2: printf("input k :"); scanf("%ld", &k); if(k < 1 || k > k_value) { printf("please retry k!\n"); goto retry2; } char *array = (char *)malloc(sizeof(char) * k_value * n); list_all_array(n, array, 0); printf("result is :\n"); for(int m = 0; m < n; m++) { printf("%c", array[(k - 1) * n + m] ); } printf("\n"); free(array); return 0; }
代码2020.7.15更新:
考虑到list_all_array
中用到的数组a[MAX]
为全局变量,可不作为输入形参,故删去了void list_all_array(int n, char* mid_array, char *full_array, int cur)
中的char* mid_array
这一输入形参。
最本质的思想还是通过递归调用list_all_array函数实现全排列枚举。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。