输出1-n的全排列c语言
时间: 2023-09-02 18:09:41 浏览: 104
好的,以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void dfs(int* nums, int n, int index, int** res, int* returnSize) {
if (index == n) { // 如果当前路径的长度已经等于n,说明已经找到了一组解
res[*returnSize] = (int*)malloc(n * sizeof(int));
memcpy(res[*returnSize], nums, n * sizeof(int));
(*returnSize)++;
return;
}
for (int i = index; i < n; i++) {
swap(&nums[index], &nums[i]); // 将nums[i]和nums[index]交换
dfs(nums, n, index + 1, res, returnSize); // 递归搜索下一层
swap(&nums[index], &nums[i]); // 回溯,将nums[i]和nums[index]交换回来
}
}
int** permute(int n, int* returnSize, int** returnColumnSizes) {
int* nums = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
int size = 1;
for (int i = 1; i <= n; i++) {
size *= i;
}
int** res = (int**)malloc(size * sizeof(int*));
*returnColumnSizes = (int*)malloc(size * sizeof(int));
*returnSize = 0;
dfs(nums, n, 0, res, returnSize);
for (int i = 0; i < *returnSize; i++) {
(*returnColumnSizes)[i] = n;
}
return res;
}
int main() {
int n = 3;
int returnSize;
int* returnColumnSizes;
int** res = permute(n, &returnSize, &returnColumnSizes);
for (int i = 0; i < returnSize; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果与之前的C++代码实现一致:
```
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
```
阅读全文