0
点赞
收藏
分享

微信扫一扫

输出全排列(20 分)

老榆 2023-05-25 阅读 72


请编写程序输出前n个正整数的全排列(n<10),并通过9个测试用例(即n从1到9)观察n逐步增大时程序的运行时间。

输入格式:

输入给出正整数n<10)。

输出格式:

输出1到n的全排列。每种排列占一行,数字间无空格。排列的输出顺序为字典序,即序列a1,a2,⋯,an排在序列b1,b2,⋯,bn之前,如果存在k使得a1=b1,⋯,ak=bk 并且 ak+1<bk+1

输入样例:

3

输出样例:

123
132
213
231
312
321


#include <bits/stdc++.h>
using namespace std;
void Print(int a[], int n)
{
    for(int i = 1; i <= n; ++i)
        printf("%d", a[i]);
    printf("\n");

}
void Go(int *a, int *temp, int n, int step)
{
    if(step == n + 1)
    {
        Print(a, n);
    }
    else
    {
        for(int i = 1; i <= n; ++i)
        {
            if(temp[i] == 0)
            {
                a[step] = i;
                temp[i] = 1;
                Go(a, temp, n, step + 1);
                temp[i] = 0;
            }
        }
    }
}
int main()
{
    int n, step = 1;
    int temp[12], a[12];
    for(int i = 1; i <= 9; ++i)
    {
        temp[i] = 0;
    }
    scanf("%d", &n);
    Go(a, temp, n, step);
}



举报

相关推荐

0 条评论