把 1~n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。
一个整数n。
按照从小到大的顺序输出所有方案,每行1个。
首先,同一行相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。
1≤n≤9
3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
#include<iostream>
using namespace std;
const int N = 16;
int num[N];
bool st[N];
int n;
void dfs(int u)
{
if(u > n)
{
for(int i = 1; i <= n; i++)
{
cout << num[i] << " ";
}
cout << endl;
return;
}
for(int i = 1; i <= n; i++)
{
if(!st[i])
{
num[u] = i;
st[i] = true;
dfs(u+1);
// 恢复现场
// num[u] = 0;
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(1);
return 0;
}
#include<iostream>
#include<vector>
using namespace std;
const int N = 10;
int n;
vector<int> path;
void dfs(int u, int state)
{
if(u == n)
{
for(int x : path) cout << x << " ";
puts("");
return;
}
for(int i = 0; i < n; i++)
{
// 看哪个第i位是0,表示还没有枚举过
if(!(state >> i & 1))
{
path.push_back(i+1);
dfs(u+1, state | 1 << i);
// 恢复现场
path.pop_back();
}
}
}
int main()
{
cin >> n;
dfs(0, 0);
return 0;
}
原文:https://www.cnblogs.com/ApStar/p/13872474.html