排列数字(全排列)
给定一个整数n,将数字1~n排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数n。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1≤n≤7
输入样例
3
输出样例
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
算法1
DFS递归
C++ 代码
#include<iostream>
//#include<bits/stdc++.h>
using namespace std;
const int N=8;
int ans[N];
int st[N];
//n:当前层的深度
void dfs(int n,int m){
if(n==m){
//输出当前方案
for(int i=0;i<n-1;i++){
cout << ans[i] << " ";
}
cout << ans[m-1] << endl;
return ;
}
for(int i=1;i<=m;i++){
if(!st[i]){
ans[n]=i;
st[i]=1;
dfs(n+1,m);
st[i]=0; //恢复状态
}
}
}
int main(){
int n;
cin >> n;
dfs(0,n);
}