Description
按照字典序输出自然数 11 到 �n 所有不重复的排列,即 �n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
Input
一个整数 �n。
Output
由 1∼�1∼n 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 55 个场宽。
Sample 1
Inputcopy | Outputcopy |
---|---|
3 | 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 |
Hint
1≤�≤91≤n≤9。
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define int ll
using namespace std;
const int N=1e6+7;
int n;
int a[N],vis[N];
void dfs(int x)
{
if(x==n+1)
{
for(int i=1;i<=n;i++) cout<<setw(5)<<a[i];
cout<<endl;
return;
}
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
a[x]=i;
vis[i]=1;
dfs(x+1);
vis[i]=0;
}
}
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
memset(vis,0,sizeof vis);
dfs(1);
return 0;
}