-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_nCr.cpp
80 lines (61 loc) · 1.57 KB
/
GFG_nCr.cpp
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
/*
https://practice.geeksforgeeks.org/problems/ncr1019/1#
nCr
*/
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
const int mod = 1e9+7;
/*
// TLE
// int failed in 1st case 15 3
// long failed in 11th case 778 116
int nCr(int n, int r){
if(r>n)
return 0;
vector<long> fac(n+1, 0);
fac[0] = 1;
fac[1] = 1;
for(int i=2; i<=n; i++)
{
fac[i] = fac[i-1]*i;
// cout<<fac[i]<<" ";
}
long ans = fac[n]/((fac[n-r])*(fac[r]));
return ans;
}
*/
int nCr(int n, int r){
if(r>n) return 0;
if (r > n - r) // Optimization for the cases when r is large
r = n - r;
vector<vector<int>> memo(n+1, vector<int>(r+1, -1));
return solve(n, r, memo);
}
int solve(int n, int r, vector<vector<int>>& memo)
{
if(n<r) return memo[n][r] = 0;
if(n==r || r==0) return memo[n][r] = 1;
if(r==1) return memo[n][r] = n;
if(memo[n][r] != -1)
return memo[n][r];
return memo[n][r] = (solve(n-1, r-1, memo) + solve(n-1, r, memo))%mod;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n, r;
cin>>n>>r;
Solution ob;
cout<<ob.nCr(n, r)<<endl;
}
return 0;
} // } Driver Code Ends