C語言實現全排列

來源:互聯網
上載者:User

標籤:pac   ++   lap   ide   深度遍曆   closed   標記   c語言   分享圖片   

一、遞迴實現全排列

 1 #include"cstdio" 2 int A[50]; 3 void print_permutation(int n,int *A,int cur){ 4         if(cur==n){ 5         for(int i=0;i<n;i++) 6             printf("%d",A[i]); 7         printf("\n"); 8         } 9         else for(int j=1;j<n+1;j++){10         int ok=1;11         for(int k=0;k<cur;k++)12             if(A[k]==j)13                 ok=0;14             if(ok){15             A[cur]=j;16             print_permutation(n,A,cur+1);17             }18         }19     }20 int main(){21     int n;22     scanf("%d",&n);23     print_permutation(n,A,0);24     return 0;25 }
View Code

 

二、解答樹

 1     #include <string.h> 2     #include <iostream> 3       4     using namespace std; 5     const int N = 99999999;     //輸入排序的個數的最大值 6     int record[N];              //記錄每次排序的序列 7     int visited[N];             //標記節點是否被訪問過 8     int n;                      //輸入節點的數目 9     int totalSize = 0;10     void DFS(int start){11         if(start>=n){           //遞迴出口12             for(int i=0;i<n;i++){13                 cout<<record[i]<<" ";14             }15             totalSize++;16             cout<<endl;17             return;18         }19         for(int i=1;i<=n;i++){      //深度遍曆節點,並標記已經訪問過的節點20             if(visited[i]==0){21                 visited[i] = 1;22                 record[start] = i;23                 DFS(start+1);       //遞迴遍曆24                 visited[i] = 0;     //回退時標記回退的節點為未被訪問節點25             }26         }27     }28      29     int main()30     {31         cin>>n;32         memset(visited,0,n);33         DFS(0);34         cout<<"totalSize = "<<totalSize<<endl;35         return 0;36     }
View Code

三、

調用next_permutation()方法

C語言實現全排列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.