Binomial Coefficient is represented by nCk which means number of ways of choosing k objects from n objects.It is the coefficient of x^k term in the polynomial expansion of (1+x)^n.It also represents an entry in Pascals Triangle.
The task is to find the value of nCk given the values of n and k.
int binomialCoeff(int n, int k)
// Base Cases
if (k==0 || k==n)
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
For large values of n,there will be many common subproblems.For example-
To calculate 5C2,function will be called for 4C2 and 4C1.
To calculate 4C1,function will be again called for 3C0 and 3C1.
To calculate 4C2,function will be called for 3C1 and 3C2.
So,3C1 is being calculated twice.
This problem has overlapping sub-problems property.Re-computation of same sub-problems can be avoided by constructing a temporary array C and storing the results like we do in other dynamic programming problems.
DP based solution-
//C is the temp array
//C[n][k] gives the result
Time Complexity of this code is O(n*k).
n,k are non negative integers.
nCk is valid only for n>0 and 0<=k<=n.