Friday, November 24, 2017

Part-2 , Find nCr ( BinomialCoefficient ) for given n and r

                                     Find nCr for given n and r


                                                  Use Recursive Formula ,
                                               
#include<bits/stdc++.h>

using namespace std;

int BinomialCoefficient(int n,int k)

{
    if(k==0||k==n)
        return 1;

    return BinomialCoefficient(n-1,k-1)+BinomialCoefficient(n-1,k);
}

int main()

{
    int n,k;
    cin>>n>>k;
    cout<<BinomialCoefficient(n,k)<<endl;
    return 0;
}

                                                            Use Of Dynamic Programming

                                                            Time Complexity  O(n*k)

  


#include<bits/stdc++.h>

using namespace std;

int BinomialCoefficient(int n,int k)

{
   int dp[n+1][k+1];
   int i,j;
   for(int i=0;i<=n;i++)
   {
       for(int j=0;j<=min(i,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;
    cin>>n>>k;
    cout<<BinomialCoefficient(n,k)<<endl;
    return 0;
}


                                            A    Problem  & It's Solution 

https://practice.geeksforgeeks.org/problems/ncr/0 


#include<bits/stdc++.h>

using namespace std;

// Nayeem Shahriar Joy , Applied Physics & Electronic Engineering,University of Rajshahi.

int BinomialCoefficient(int n,int k)

{
   int dp[n+1][k+1];
   int i,j;
   for(int i=0;i<=n;i++)
   {
       for(int j=0;j<=min(i,k);j++)
       {
           if(j==0||j==i)
            dp[i][j]=1;
           else
            dp[i][j]=(dp[i-1][j-1]+dp[i-1][j])%1000000007;
       }
   }
   return dp[n][k];
}

int main()

{
    int t;
    cin>>t;
    while(t--){
    int n,k;
    cin>>n>>k;
    if(n<k)
    {
        cout<<"0"<<endl;
    }
    else{
    cout<<BinomialCoefficient(n,k)<<endl;
    }
    }
    return 0;
}












No comments:

Post a Comment