This is a C++ Program that Solves Binomial Coefficients Problem using Dynamic Programming technique.
Given two values n and k, find the number of ways of chosing k objects from among n objects disregarding order.
The problem can be rephrased as finding the binomail coefficient C(n,k).
The problem is to find C(n,k). But this might turn out to be inefficient. So, we will find the binomial coefficient rather than finding C(n,k) by calculating factorials. We can find the binomial coefficient in the same way as we build the pascal’s triangle proceeding in a bottom up fashion.
Case-1:
n=3, k=2 Expected result=3
Here is source code of the C++ Program to Solve Binomial Coefficients Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<iostream>
using namespace std;
int binomialCoefficient(int n, int k)
{
int dp[n+1][k+1];
int i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=i && j<=k;j++)
{
if(j==0 || j==i)
dp[i][j]=1;
else
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp[n][k];
}
int main()
{
int n, k;
cout<<"Enter the total number of objects "<<endl;
cin>>n;
cout<<"Enter how many elements to be chosen out of "<<n<<" objects "<<endl;
cin>>k;
if(n<0 ||k<0 || k>n)
cout<<"Invalid input";
else
{
cout<<"The number of ways in which selections can be made is "<<endl;
cout<<binomialCoefficient(n,k);
}
cout<<endl;
return 0;
}
In the main function, we ask the user to input the value for number of objects to be chosen and the total number of objects. We pass these values to the function binomialCoefficient as parameters. This function will calculate the expected result and return it. The returned value will be displayed.
Case-1: $ g++ binomial_coefficient.cpp $ ./a.out Enter the total number of objects 3 Enter how many elements to be chosen out of 3 objects 2 The number of ways in which selections can be made is 3
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Programming Books
- Apply for Information Technology Internship
- Buy Computer Science Books
- Practice Programming MCQs
- Practice Computer Science MCQs