请编写程序输出前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<iostream>
#include<vector>
using namespace std;
bool chosen[10];
int order[10];
void cal(int x, int n)
{
if (x == n + 1)
{
for (int i = 1; i <= n; i++)
{
cout << order[i];
}
cout << endl;
return;
}
for (int i = 1; i <= n; i++)
{
if (chosen[i]) continue;
order[x] = i;
chosen[i]=1;
cal(x + 1, n);
chosen[i]=0;
order[x] = 0;
}
}
int main()
{
int n;
cin >> n;
cal(1, n);
}