c语言用递归生成整数的全排列
时间: 2024-05-06 14:15:08 浏览: 10
以下是使用递归在 C 语言中生成整数的全排列的示例代码:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void permute(int arr[], int start, int end) {
if (start == end) {
// 打印排列
for (int i = 0; i <= end; i++) {
printf("%d ", arr[i]);
}
printf("\n");
} else {
// 生成排列
for (int i = start; i <= end; i++) {
swap(&arr[start], &arr[i]);
permute(arr, start + 1, end);
swap(&arr[start], &arr[i]);
}
}
}
int main() {
int arr[] = {1, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
permute(arr, 0, n - 1);
return 0;
}
```
在这个示例中,`permute` 函数使用递归生成整数的全排列。`swap` 函数用于交换数组中的两个元素。在 `permute` 函数中,如果 `start` 等于 `end`,则打印数组中的排列。否则,我们对数组中从 `start` 到 `end` 的元素进行交换,并递归计算从 `start + 1` 到 `end` 的排列,最后再将交换的元素交换回来。在主函数中,我们将整数数组 `{1, 2, 3}` 传递给 `permute` 函数,并打印所有排列。