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 );
}