Permutation and combinatorial algorithms are common algorithms for examining recursion, and these two algorithms can be implemented in a recursive and concise way.
After many groping and thinking, I summarize the following for reference. The program code is as follows:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4CharArray[] = "ABCD";
5
6 #define N 4
7 #define M 3
8intQueue[n] = {0};
9inttop = 0;
10intFlag[n] = {0};
11
12voidPermintSintN
13 {
14intI
15
16if(S > N)
17 {
18 return;
19}
20
21stif(s = = N)
22 {
23 for(i = 0; i < n; i++)
24 {
printf ("%c", Queue[i]);
26}
-printf ("T");
28 return;
29}
30
31 for(i = 0; i < n; i++)
32 {
33if(Flag[i] = = 0)
34 {
Flag[i] = 1;
Queue[s] = Array[i];
Panax Notoginseng Perm (s+1, N);
Flag[i] = 0;
39}
40}
41}
42
43voidComb (intSintNintM
44 {
45intI
46
47if(S > N)
48 return;
49
50if(top = = m)
51 {
52 for(i = 0; i < m; i++)
53 {
printf ("%c", Queue[i]);
55}
printf ("T");
57 return;
58}
59
queue[top++] = Array[s];
Comb (s+1, n, m);
top--;
Comb (s+1, n, m);
64
65}
66
67intMain ()
68 {
In printf ("\nperm (): \ n");
Perm (0, N);
In printf ("\ncombination (): \ n");
Comb (0, N, M);
printf ("\ n");
74 return0;
75}
Run Result: 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