用c++的方式编程1~8的全排列,按照全排列的顺序输出,每行结尾无空格。
时间: 2023-03-22 21:02:11 浏览: 89
很高兴能回答您的问题。使用C语言编程1~8的全排列,按照全排列的顺序输出,每行结尾无空格,可以使用递归的方法来实现。下面是示例代码: void printPermutation(int *num, int n, int i)
{
if (i == n)
{
for (int j = 0; j < n; j++)
printf("%d", num[j]);
printf("\n");
return;
}
for (int j = i; j < n; j++)
{
swap(&num[i], &num[j]);
printPermutation(num, n, i + 1);
swap(&num[i], &num[j]);
}
}
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
int num[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof(num) / sizeof(num[0]);
printPermutation(num, n, 0);
return 0;
}
相关问题
c++整数1到n的全排列,每行输出一个排列,排列的各元素用空格分隔。
好的,下面是给您的代码实现,可以实现1到n的全排列输出:
```c
#include <stdio.h>
int n;
int a[100];
void swap(int *a, int *b) {
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void perm(int start, int end) {
int i;
if (start == end) {
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
} else {
for (i = start; i <= end; i++) {
swap(&a[start], &a[i]);
perm(start + 1, end);
swap(&a[start], &a[i]);
}
}
}
int main() {
scanf("%d", &n);
int i;
for (i = 0; i < n; i++) {
a[i] = i + 1;
}
perm(0, n - 1);
return 0;
}
```
希望可以帮到您!
用c++编程输出5以内全排列
以下是用C语言编写的输出5以内全排列的程序:
```c
#include <stdio.h>
void permute(int a[], int start, int end);
void swap(int *x, int *y);
int main() {
int a[] = {1, 2, 3, 4, 5};
permute(a, 0, 4);
return 0;
}
void permute(int a[], int start, int end) {
int i;
if (start == end) {
for (i = 0; i <= end; i++) {
printf("%d ", a[i]);
}
printf("\n");
} else {
for (i = start; i <= end; i++) {
swap(&a[start], &a[i]);
permute(a, start + 1, end);
swap(&a[start], &a[i]);
}
}
}
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;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