-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinomialCoefficient.cpp
More file actions
98 lines (98 loc) · 2.17 KB
/
BinomialCoefficient.cpp
File metadata and controls
98 lines (98 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include<iostream>
using namespace std;
//Time Complexity is exponential And Space Complexity is O(n)
int binoCoff(int n,int r)
{
if(n==r || r==0)
{
return 1;
}
else
{
return binoCoff(n-1,r) + binoCoff(n-1,r-1);
}
}
//Time Complexity is O(n*k) And Space Complexity is O(n*k)
int binoCoffDP(int n,int r)
{
int **ar=new int*[n+1];
for(int i=0;i<=n;i++)
{
ar[i]=new int[r+1];
}
for(int i=0;i<=n;i++)
{
for(int j=0;j<=min(i,r);j++)
{
if(i==j || j==0)
{
ar[i][j]=1;
}
else
{
ar[i][j]=ar[i-1][j-1]+ar[i-1][j];
}
}
}
return ar[n][r];
}
//Time complexity is O(n*r) And Space Complexity is O(r)
int binoCoffDP2(int n,int r)
{
int *ar=new int[r+1];
for(int i=0;i<=r;i++)
{
ar[i]=0;
}
ar[0]=1;
for(int i=1;i<=n;i++)
{
for(int j=min(i,r);j>0;j--)
{
ar[j]+=ar[j-1];
}
}
return ar[r];
}
//Time Complexity is O(n*k) And Space complexity is O(n)
int binoCoffDP3(int n,int r,int **dp)
{
if(dp[n][r]!=-1)
{
return dp[n][r];
}
if(r==n || r==0)
{
dp[n][r]=1;
return dp[n][r];
}
else
{
dp[n][r]=binoCoffDP3(n-1,r-1,dp)+binoCoffDP3(n-1,r,dp);
return dp[n][r];
}
}
int main()
{
int n,r;
cout<<"Enter the value of n and r :\n";
cin>>n;
cin>>r;
cout<<"The Binomial Coefficient using recursion of C("<<n<<","<<r<<") is : "<<binoCoff(n,r)<<endl;
cout<<"The Binomial Coefficient using DP of C("<<n<<","<<r<<") is : "<<binoCoffDP(n,r)<<endl;
cout<<"The Binomial Coefficient using DP2 of C("<<n<<","<<r<<") is : "<<binoCoffDP2(n,r)<<endl;
int **dp=new int*[n+1];
for(int i=0;i<=n;i++)
{
dp[i]=new int[r+1];
}
for(int i=0;i<=n;i++)
{
for(int j=0;j<=r;j++)
{
dp[i][j]=-1;
}
}
dp[0][0]=1;
cout<<"The Binomial Coefficient using DP3 of C("<<n<<","<<r<<") is : "<<binoCoffDP3(n,r,dp);
}