排列组合问题C(m,n)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MOU_IT/article/details/87809119

1、直接求解    

  对于求解排列组合问题C<m,n>,第一种求解方式是直接求解,也就是采用数学上的公式,即

                                     C<m,n> =  A<m, n> / A<n, n>

  对于这种求解方式而言,所使用的额外空间比较少,但是这种求解方式的时间复杂度是非常大的,因此我们在求解这个问题时,不推荐这种直接的求解方式。

2、使用杨辉三角方式

    第二种求解排列组合问题的方式是使用杨辉三角的方式,采用动态规划的方法求解,具体而言,其递推公式为:

                                   C(n,k) = C(n-1,k) + C(n-1,k-1)

对应于杨辉三角

1

1   1

1   2   1

1   3   3   1

1   4   6   4   1

用C++实现为:

#include<iostream>
using namespace std;

long SortConbine(int m, int n)
{    
    //创建杨辉三角矩阵并初始化
    long** temp = new long*[m + 1];
    for (int i = 0; i <= m; i++)
        temp[i] = new long[m + 1];
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= m; j++)
            temp[i][j]=0;
    }
    
    //根据杨辉三角计算排列组合问题
    temp[0][0] = 1;
    for (int i = 1; i <= m; i++) {
        temp[i][0] = 1;
        for (int j = 1; j <= m; j++) {
            temp[i][j] = (temp[i - 1][j - 1] + temp[i - 1][j]) % mod;
        }
    }

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= m; j++)
            cout << temp[i][j] << '\t';
        cout << endl;
    }
    return temp[m][n];

猜你喜欢

转载自blog.csdn.net/MOU_IT/article/details/87809119