简体   繁体   English

动态规划和一维数组的二项式系数算法

[英]binomial coefficient algorithm using dynamic programming and a single dimensional array

I'm know a dynamic programming algorithm to compute the binomial coefficients with two-dimensional array like below . 我知道一种动态编程算法,可以像下面这样用二维数组来计算二项式系数。 Is there any way to make use of one-dimensional array? 有没有办法利用一维数组?

int binomialCoeff(int n, int k)
{
int C[n+1][k+1];
int i, j;


for (i = 0; i <= n; i++)
 {
   for (j = 0; j <= min(i, k); j++)
    {

        if (j == 0 || j == i)
            C[i][j] = 1;


        else
            C[i][j] = C[i-1][j-1] + C[i-1][j];
    }
    }

  return C[n][k];
  }

Your Dynamic Programming method (using 2D array) to solve Binomial Coefficient, seems correct. 您的动态编程方法(使用2D数组)求解二项式系数,似乎是正确的。 Note that we do not need to keep the whole table, only the prior row. 请注意,我们不需要保留整个表,而只保留前一行。 So 1D implementation is possible! 因此,一维实施成为可能!

Below is the code to implement it using a 1D array. 以下是使用一维数组实现该代码的代码。

    int binomial_coefficient(int n, int k)
    {
          int C[k+1];int i,j;
          for(i=0;i<=k;i++)
                 C[i]=0;
          C[0]=1;
          for(i=1;i<=n;i++)
          {
                 for(j=min(i,k);j>0;j--)
                         C[j]=C[j]+C[j-1];
          }
          return C[k];
    }

Two dimensional arrays can be easily represented as one dimensional arrays. 二维数组可以很容易地表示为一维数组。

instead of defining C[n+1][k+1] , define some C2[(n+1)*(k+1)] . 而不是定义C[n+1][k+1] ,而是定义一些C2[(n+1)*(k+1)] Then, instead of calling C[a][b] call C2[b*(n+1)+a] . 然后,代替调用C[a][b]调用C2[b*(n+1)+a]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM