0

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];
  }
1
  • Welcome. It seems there is a problem with { and }, and the first line of the code in not formatted as code. Commented Mar 7, 2015 at 20:17

2 Answers 2

2

Your Dynamic Programming method (using 2D array) to solve Binomial Coefficient, seems correct. 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];
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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)]. Then, instead of calling C[a][b] call C2[b*(n+1)+a].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.