排列和組合演算法是考查遞迴的常見演算法,這兩種演算法能用遞迴簡潔地實現。
本人在經過多次摸索和思考之後,總結如下,以供參考。 程式碼如下:
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