Acwing 842. 排列数字(STL & DFS)
给定一个整数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
题解
STL的next_permutation()
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, a[N];
int main(){
cin >> n;
for (int i = 0 ; i < n ; i ++ ) a[i] = i + 1;
int t = 1;
for (int i = 1 ; i <= n ; i ++ ) t *= i;
for (int i = 0 ; i < t ; i ++ ){
for (int i = 0 ; i < n ; i ++ ) cout << a[i] << ' ';
next_permutation(a, a + n);
cout << endl;
}
return 0;
}
dfs
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, tra[N];
bool flag[N];
void dfs(int x){
if (x > n){
for (int i = 1 ; i <= n ; i ++ ) cout << tra[i] << ' ';
cout << endl;
return;
}
for (int i = 1 ; i <= n ; i ++ ){
if (!flag[i]){
flag[i] = true;
tra[x] = i;
dfs(x + 1);
tra[x] = -1;
flag[i] = false;
}
}
}
int main(){
cin >> n;
dfs(1);
return 0;
}