排列和組合演算法 C語言經典實現

來源:互聯網
上載者:User

排列和組合演算法是考查遞迴的常見演算法,這兩種演算法能用遞迴簡潔地實現。

本人在經過多次摸索和思考之後,總結如下,以供參考。 程式碼如下:


 1 #include <stdio.h>
 2 #include <stdlib.h>
 3
 4 char array[] = "abcd";
 5
 6 #define N  4
 7 #define M  3
 8 int queue[N] = {0};
 9 int top = 0;
10 int flag[N] = {0};
11
12 void perm(int s, int n)
13 {
14     int i;
15
16     if (s > n)
17     {
18         return;
19     }
20
21     if (s == n)
22     {
23         for (i = 0; i < n; i++)
24         {
25             printf("%c", queue[i]);
26         }
27         printf("\t");
28         return ;
29     }
30
31     for (i = 0; i < n; i++)
32     {
33         if (flag[i] == 0)
34         {
35             flag[i] = 1;
36             queue[s] = array[i];
37             perm(s+1, n);
38             flag[i] = 0;
39         }
40     }
41 }
42
43 void comb(int s, int n, int m)
44 {
45     int i;
46
47     if (s > n)
48         return ;
49
50     if (top == m)
51     {
52         for (i = 0; i < m; i++)
53         {
54             printf("%c", queue[i]);
55         }
56         printf("\t");
57         return ;
58     }
59
60     queue[top++] = array[s];
61     comb(s+1, n, m);
62     top--;
63     comb(s+1, n, m);
64
65 }
66
67 int main()
68 {
69     printf("\nperm():\n");
70     perm(0, N);
71     printf("\ncombination():\n");
72     comb(0, N, M);
73     printf("\n");
74     return 0;

75 }


運行結果: perm():
abcd    abdc    acbd    acdb    adbc    adcb    bacd    badc    bcad    bcda
bdac    bdca    cabd    cadb    cbad    cbda    cdab    cdba    dabc    dacb
dbac    dbca    dcab    dcba
combination():
abc     abd     acd     bcd


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.