Permutation and combination algorithm (upgraded version)

Preface
In the last blog, we shared the general permutation and combination algorithm ( if you haven’t read it, click here~ ), but the shortcomings are obvious, it is impossible to perform modular operations, and the calculation range is very limited, and the permutation and combination shared today The upgraded algorithm can easily solve these problems. Without further ado, let’s start learning today!
Insert image description here

Code Implementation
First we need to know these formulas
C(n,k) = C(n-1,k) + C(n-1,k-1) (C(n,k) refers to selecting k from n elements number of elements)
A(n,k) = (nk)! * c(n,k)
Knowing this formula, we can set the array C[I][J] to represent C(I,J), and the array A [I][J] represents A(i,j), and the array f[i] represents i! , the recursive formula obtains the value of the permutation and combination. During initialization, when j is 0, c[i][j] is assigned a value of 1, which means that there is only one way to select 0 elements from i elements; otherwise, c[ i][j] = c[i-1][j] + c[i-1][j-1] means calculating the number of combinations based on the recursion relationship. Second, calculate the factorial by looping. Factorial f(n) represents the product of consecutive integers from 1 to n, that is, n!. Finally, the permutation number is calculated by combining the number and the factorial result.
code show as below:

#include<stdio.h>
#define mod 1000000007//模数
int C[1145][1145];//组合
long long F[1145];//结成
int A[1145][1145];//排列
void combination(int n)
{
    
    
    for (int i = 0; i < n; i++)//当j = 0时直接初始化为1
    {
    
    
        C[i][0] = 1;
    }
    for (int i = 1; i < n; i++)//递推公式求组合数
    {
    
    
        for (int j = 1; j <= i; j++)
        {
    
    
            C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % mod;
        }
    }
}
void factorial(int n)
{
    
    
    F[0] = 1;
    for (int i = 1; i < n; i++)//求结成
    {
    
    
        F[i] = F[i - 1] * i % mod;
    }
}
void permutation(int n)
{
    
    
    for (int i = 0; i < n; i++)//递推公式求排列数
    {
    
    
        for (int j = 0; j <= i; j++)
        {
    
    
            A[i][j] = F[i - j] * C[i][j] % mod;
        }
    }
}
int main()
{
    
    
int n = 1145;
    combination(n);
    factorial(n);
    permutation(n);
    return 0;
}

This is the upgraded version of the permutation and combination algorithm. In the future, friends will be able to pick up this type of questions easily. If you think the blogger’s words are good, don’t forget to give the blogger a follow, like, and collection to encourage him. ~, see you next time!

Guess you like

Origin blog.csdn.net/Tokai___Teio/article/details/135259931