用递归来实现全排列问题:
全排列就是假设1~3的全排列就为:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
可以看出假设本来只有三个位置 __ __ __
首先选择一个1(要保证字典序)
1 __ __
下一个位置只需要保证不再是1即可
就这样一直回溯就能得到最终结果
详细递归过程请参考:这篇
结合代码分析:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <string>
#define ll long long
#define mod 1e9 + 7
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
#define IOS ios::sync_with_stdio(false);
using namespace std;
int n;
int a[20], book[20];
void dfs(int x)
{
if(x == n + 1) // 到达最后一个位置
{
for(int i = 1; i <= n; i ++) cout << a[i] << " "; // 输出此时答案
cout << endl;
return ;
}
for(int i = 1; i <= n; i ++)
{
if(!book[i]) // 这个数没选
{
a[x] = i; // 记录选了那些数
book[i] = 1; // 标记不能在用这个数
dfs(x + 1); // 下一个位置
book[i] = 0; // 回溯
}
}
}
int main()
{
cin >> n;
dfs(1);
return 0;
}