DFS:
#include <iostream>
using namespace std;
const int N = 20;
int n,p[N];
bool st[N];
void dfs(int x)
{
if(x==n)
{
for(int i=0;i<n;i++) printf("%d ",p[i]);
printf("\n");
return ;
}
for(int i=1;i<=n;i++)
{
if(!st[i])
{
p[x] = i;
st[i] = true;
dfs(x+1);
p[x] = 0; //回溯
st[i] = false;
}
}
}
int main()
{
cin>>n;
dfs(0);
return 0;
}
STL_next_permutation():
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 20;
int n,p[N];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
p[i] = i;
}
do{
for(int i=1;i<=n;i++)
{
cout<<p[i]<<" ";
}
printf("\n");
}while(next_permutation(p+1,p+n+1));
return 0;
}