Permutation and combinatorial algorithm C language Classic implementation

Source: Internet
Author: User

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.