求1~n全排列:
#include <cstdio>
#include <cstring>
using namespace std;
void dfs(int cur);
int vis[10], A[10], n;
int main()
{
memset(vis, 0, sizeof(int) * 10);
while (scanf("%d", &n) == 1)
dfs(1);
return 0;
}
void dfs(int cur)
{
if (cur == n + 1)
{
for (int i = 1; i <= n; i++)
printf("%d ", A[i]);
printf("\n");
}
else
for (int i = 1; i <= n; i++)
{
if (vis[i] == 0)
{
A[cur] = i;
vis[i] = 1;
dfs(cur+1); // 递归时每层函数的cur互相独立,并不随调用改变,返回后会被覆盖(类似滚动数组)
vis[i] = 0;
}
}
}