The implementation method of permutation and combination algorithm _c Language classic case _c language

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:

#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 ~

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.