问题 K: 递归实现排列型枚举
时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
把 1~n 这 n(n<10) 个整数排成一行后随机打乱顺序,输出所有可能的次序。
输入
一个整数n。
输出
按照从小到大的顺序输出所有方案,每行1个。 首先,同一行相邻两个数用一个空格隔开。其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。
样例输入 Copy
3
样例输出 Copy
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
#include <vector>
using namespace std;
int n;
vector<int> path;
vector<int>::iterator iter = path.begin();
void dfs(int u,int state){
if(u == n){
//for(auto x : path) cout<<x<<' ';
iter=path.begin();
for(;iter!=path.end();iter++)
cout<<*iter<<' ';
cout<<endl;
return ;
}
for(int i=0;i<n;i++){
if(!(state>>i&1)){
path.push_back(i+1);
dfs(u+1,state|(1<<i));
path.pop_back();
}
}
}
int main()
{
cin>>n;
dfs(0,0);
return 0;
}