#include<cstdio>#include<algorithm>
using namespace std;intmain(){int n;int a[20];while(scanf("%d",&n)!=EOF){for(int i =0; i < n ; i++){
a[i]= i+1;}do{for(int i =0; i < n ; i++){if(i ==0){printf("%d",a[i]);}else{printf(" %d",a[i]);}}printf("\n");}while(next_permutation(a,a+n));}return0;}
用深度优先搜索算法
#include<iostream>
using namespace std;int num[11];
bool vis[11]={false};int n;voiddfs(int index){if(index == n){for(int i =0; i < n-1; i++){printf("%d ",num[i]);}printf("%d\n",num[n-1]);}for(int i =0; i < n ; i++){if(vis[i+1]== false){
num[index]= i+1;
vis[i+1]= true;dfs(index+1);
vis[i+1]= false;}}}intmain(){while(scanf("%d",&n)!=EOF){dfs(0);}return0;}