dfs——n的全排列(回溯)

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <map>
 5 #include <set>
 6 #include <algorithm>
 7 #include <fstream>
 8 #include <cstdio>
 9 #include <cmath>
10 #include <stack>
11 #include <queue>
12 #define lson l,m,rt<<1
13 #define rson m+1,r,rt<<1|1
14 using namespace std;
15 const double Pi=3.14159265358979323846;
16 typedef long long ll;
17 const int MAXN=200000+5;
18 const int dx[5]={0,0,0,1,-1};
19 const int dy[5]={1,-1,0,0,0};
20 const int INF = 0x3f3f3f3f;
21 const int NINF = 0xc0c0c0c0;
22 const ll mod=1e9+7;
23 int n;
24 int flag[MAXN],a[MAXN];
25 int cnt=1;
26 int t;
27 
28 void dfs(int t)
29 {
30     if(t==0)
31     {
32         for(int i=1;i<=n;i++)
33         {
34             cout << a[i]<<" ";
35         }
36         cout <<endl;
37         return;
38     }
39     for(int i=1;i<=n;i++)
40     {
41         if(flag[i]==0) 
42         {
43             flag[i]=1;
44             a[cnt++]=i;
45             //cout <<a[cnt-1]<<" ";
46             dfs(t-1);
47             cnt--;flag[i]=0;
48         }
49         
50     }
51 }
52 int main()
53 {
54     while(scanf("%d",&n)&&n)
55     {
56         t=n;
57         dfs(t);
58     }
59     return 0;
60 }

猜你喜欢

转载自www.cnblogs.com/Msmw/p/10520103.html
今日推荐