em……这玩意其实就是……返回结果再输出
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> com(vector<int> &v)
{
vector<vector<int>> res;
if (v.size() == 1)
{
res.push_back(v);
return res;
}
for (int i = 0; i < v.size(); i ++)
{
int tmp = v[i];
v.erase(v.begin() + i, v.begin() + i + 1);
auto c = com(v);
v.insert(v.begin() + i, tmp);
for (auto p : c)
{
vector<int> t;
t.push_back(v[i]);
for (int x : p) t.push_back(x);
res.push_back(t);
}
}
return res;
}
int main()
{
int n; cin >> n;
vector<int> t;
for (int i = 1; i <= n; i ++) t.push_back(i);
auto res = com(t);
for (auto v : res)
{
for (auto x : v) cout << x << ' ';
cout << "\n";
}
return 0;
}
现在我写的:
#include <iostream>
using namespace std;
const int N = 11;
int n;
int a[N];
bool st[N];
void dfs(int u)
{
if (u >= n)
{
for (int i = 0; i < n; i ++ ) cout << a[i] << ' ';
puts("");
return ;
}
for (int i = 1; i <= n; i ++ )
if (!st[i])
{
st[i] = true, a[u] = i;
dfs(u + 1);
st[i] = false;
}
}
int main()
{
cin >> n;
dfs(0);
return 0;
}