题目描述
给定一个整数 $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时的模拟过程
[HTML_REMOVED]
C++ 代码
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10;
int path[N]; // 用来存储一次深度优先搜索的路径
bool st[N]; // 用来标记对应数字是否已经参与排列
int n;
void dfs(int u)
{
if (u == n) // 一次深搜结束
{
for(int i=0; i<n; i++) printf("%d ", path[i]);
puts("");
return;
}
for (int i=1; i<=n; i++)
{
if (!st[i]) // 判断对应数字是否已经参与排列
{
path[u] = i;
st[i] = true;
dfs(u+1);
st[i] = false; //恢复现场
}
}
}
int main()
{
cin>>n;
// 从初始位置开始进行深搜
dfs(0);
return 0;
}