题目
给定一个整数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
代码
dfs最重要的就时每一次回溯都要回复状态。
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1e2 + 7;
int n;
int path[N];
bool s[N];//来表示某个点是否走过了
void dfs(int u) {
if (u == n) {
for (int i = 1; i <= u; i++)cout << path[i];
cout << "\n";
}
else {
for (int i = 1; i <= n; i++) {
if (!s[i]) {
s[i] = true;
path[u] = i;//改变状态
dfs(u + 1);
s[i] = false;//回复状态
}
}
}
}
int main() {
cin >> n;
dfs(1);
system("pause");
}