c语言实现数组全排列
时间: 2023-09-29 09:06:49 浏览: 140
C语言实现全排列算法模板的方法
要在C语言中实现数组的全排列,可以使用递归方法。以下是两种不同的实现方法:
方法一:
```c
#include <stdio.h>
#include <stdlib.h>
void swap(int arr[], int a, int b) {
int temp = arr[a];
arr[a = arr[b];
arr[b = temp;
}
void perm(int a[], int begin, int n) {
if (begin == n) {
for (int i = 0; i <= n; i++) {
printf("%d ", a[i]);
}
printf("\n");
} else {
for (int k = begin; k <= n; k++) {
swap(a, begin, k);
perm(a, begin + 1, n);
swap(a, begin, k);
}
}
}
int main() {
int* a;
int n;
scanf("%d", &n);
a = (int*)calloc(n, sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
perm(a, 0, n - 1);
free(a);
return 0;
}
```
方法二:
```c
#include <stdio.h>
void Permutation(int m, int n, int arr[], int temp[]) {
if (m >= n) {
for (int i = 0; i < n-1; i++) {
printf("%d ", arr[i]);
}
printf("%d\n", arr[n-1]);
} else {
for (int i = 0; i < n; i++) {
if (temp[i == 0) {
temp[i = 1;
arr[m = i + 1;
Permutation(m + 1, n, arr, temp);
temp[i = 0;
}
}
}
}
int main() {
int arr = 0;
}
Permutation(0, n, arr, temp);
return 0;
}
```
以上是两种C语言实现数组全排列的方法,你可以根据需要选择其中的一种方法来使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [排列组合之——全排列(c语言)](https://blog.csdn.net/m0_74820906/article/details/127779230)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [C语言实现排列组合(全排列)](https://blog.csdn.net/weixin_45652695/article/details/104212424)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文