【题解】P1706
P1706
题目
题目描述:
按照字典序输出自然数 到 所有不重复的排列,即 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
输入格式:
一个整数 。
输出格式:
由 组成的所有不重复的数字序列,每行一个序列。
每个数字保留 个场宽。
数据范围与说明:
。
输入输出样例 #1
输入:
3
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
代码
#include<bits/stdc++.h>
using namespace std;
bool a[100];
int n;
void dfs(int pos,vector<int>&arr){
if(pos==n){
for(int &x:arr) cout<<setw(5)<<x;
cout<<endl;
return ;
}
for(int i=1;i<=n;i++){
if(!a[i]){
a[i]=true;
arr.push_back(i);
dfs(pos+1,arr);
arr.pop_back();
a[i]=false;
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
vector<int>arr;
cin>>n;
dfs(0,arr);
return 0;
}