A typical arrangement and combination algorithm in C Language

Source: Internet
Author: User

A typical arrangement and combination algorithm in C Language

In C language, the full permutation algorithm and composite number algorithm are widely used in actual problems, but there are many algorithms. I personally think that there is no need to remember too many methods. It is best to remember only one method, you can also eat them all over the day.

Full arrangement:

# Include <stdio. h>

Void swap (int * p1, int * p2)

{

Int t = * p1;

* P1 = * p2;

* P2 = t;

}

Void permutation (int a [], int index, int size)

{

If (index = size)

{

For (int I = 0; I <size; I ++)

Printf ("% d", a [I]);

Printf ("\ n ");

}

Else

{

For (int j = index; j <size; j ++)

{

Swap (& a [j], & a [index]);

Permutation (a, index + 1, size); // recursion is used here

Swap (& a [j], & a [index]);

}

}

}

Int main ()

{

Int n;

Scanf ("% d", & n );

Int a [n];

For (int I = 0; I <n; I ++)

A [I] = I + 1;

Permutation (a, 0, n );

Return 0;

}

 

 

Combination:

# Include <stdio. h>

Void combine (int n, int m, int a [], int B [], const int M)

{

For (int j = n; j> = m; j --)

{

B [s-1] = J-1;

If (m> 1) combine (J-1, S-1, a, B, M); // uses recursive thought

Else

{

For (int I = M-1; I> = 0; I --) printf ("% d", a [B [I]);

Printf ("\ n ");

}

}

}

Int main ()

{

Int n, m;

Scanf ("% d", & n, & m );

Int a [n]; int B [m];

For (int I = 0; I <n; I ++)

A [I] = I + 1;

Const int M = m;

Combine (n, m, a, B, M );

}

Related Article

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.