手搓排列型枚举递归搜索树 全排列问题(dfs)
上题:
洛谷P1706 全排列问题
递归搜索树如下:
代码:
#include<bits/stdc++.h>
using namespace std;
int n;
const int N=20;
bool st[N];
int path[N];
void dfs(int u)
{
if(u==n)
{
for(int i=0;i<n;i++)
{
printf("%5d",path[i]);
}
cout<<'\n';
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;
}