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:
#include <stdio.h> #include <stdlib.h> char array[] = "ABCD";
#define N 4 #define M 3 int Queue[n] = {0};
int top = 0;
int Flag[n] = {0};
void Perm (int s, int n) {int i;
if (s > N) {return;
} if (s = = N) {for (i = 0; i < n; i++) {printf ("%c", Queue[i]);
printf ("\ t");
return;
for (i = 0; i < n; i++) {if (flag[i] = = 0) {Flag[i] = 1;
Queue[s] = Array[i];
Perm (s+1, N);
Flag[i] = 0;
}} void Comb (int s, int n, int m) {int i;
if (s > N) return;
if (top = m) {for (i = 0; i < m; i++) {printf ("%c", Queue[i]);
printf ("\ t");
return;
} queue[top++] = Array[s];
Comb (s+1, n, m);
top--;
Comb (s+1, n, m);
int main () {printf ("\nperm (): \ n");
Perm (0, N);
printf ("\ncombination (): \ n");
Comb (0, N, M);
printf ("\ n");
return 0; }
Run Result:
Perm ():
abcd abdc acbd acdb adbc
adcb bacd badc Bcad BCDA BDCA cabd cadb cbad cbda cdab cdba dabc dacb Dbac DBCA dcab DCBA
combination ():
ABC abd ACD BCD
The above is a small set for everyone to bring the arrangement and the combination of algorithms to achieve the full range of _c Language classic cases, I hope to help you, a lot of support cloud Habitat Community ~