1.前n个自然数的所有排列:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 5 using namespace std; 6 7 int count=1,n; 8 bool *b; 9 int *a; 10 11 void dfs(int); 12 13 int main() 14 { 15 scanf("%d",&n); 16 b=new bool[n+1]; 17 a=new int[n+1]; 18 memset(b,0,n+1);//这里不能写sizeof(b),b为变量指针 19 dfs(1); 20 return 0; 21 } 22 void dfs(int t) 23 { 24 for(int i=1;i<=n;i++) 25 { 26 if(b[i]) continue; 27 b[i]=1; 28 a[t]=i; 29 if(t==n) 30 { 31 printf("%d ",count++); 32 for(int j=1;j<=n;j++) printf("%d",a[j]); 33 puts(""); 34 b[i]=0; 35 return; 36 } 37 dfs(t+1); 38 b[i]=0; 39 } 40 }