给定一个不包含重复的数组,返回所有可能的排列。C语言
时间: 2023-12-10 21:39:20 浏览: 27
以下是使用递归实现的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void permute(int *nums, int start, int end) {
if (start == end) {
for (int i = 0; i <= end; i++) {
printf("%d ", nums[i]);
}
printf("\n");
} else {
for (int i = start; i <= end; i++) {
swap(&nums[start], &nums[i]);
permute(nums, start + 1, end);
swap(&nums[start], &nums[i]);
}
}
}
int main() {
int nums[] = {1, 2, 3};
int n = sizeof(nums) / sizeof(nums[0]);
permute(nums, 0, n - 1);
return 0;
}
```
输出:
```
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
```
该算法的时间复杂度为O(n!),因为有n!种可能的排列。