全排列的递归实现
题目要求:
给出一个n, 按字典序输出1~n的全排列。
代码
代码语言:javascript复制#include
#include
void fun(int cur[], int m, int arr[], int n) {
int i, j;
if (n == 0) {
for (i = 0; i < m; i ) {
printf("%d ", cur[i]);
}
printf("n");
}
for (i = 0; i < n; i ) {
cur[m] = arr[i];
int* new_arr = (int*)malloc(sizeof(int) * (n - 1));
for (j = 0; j < n - 1; j ) {
if (j < i)new_arr[j] = arr[j];
else new_arr[j] = arr[j 1];
}
fun(cur, m 1, new_arr, n - 1);
free(new_arr);
}
}
int main() {
int n, i, cur[MAX] = { 0 }, arr[MAX];
scanf("%d", &n);
for (i = 0; i < MAX; i ) {
arr[i] = i 1;
}
fun(cur, 0, arr, n);
return 0;
}