-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_96_UniqueBST.cpp
111 lines (93 loc) · 2.53 KB
/
LC_96_UniqueBST.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
https://leetcode.com/problems/unique-binary-search-trees/
96. Unique Binary Search Trees
https://practice.geeksforgeeks.org/problems/unique-bsts-1587115621/1
*/
class Solution {
public:
int numTrees(int n) {
// t(n) = sum_{i=1 to n} t(i-1)*t(n-i)
// memo.resize(n+1, -1);
// countbst(n);
// return memo[n];
/*
vector<int> dp(n+1);
dp[0]=1; // one bst with zero node, empty bst
dp[1]=1; // one bst with one node, structurally unqiue;
// for each node in root index, number of bst in left subtree * number of bst in right subtree
for(int root=2; root<=n; root++)
{
for(int left=1; left<=root; left++)
dp[root] += dp[left-1]*dp[root-left];
}
return dp[n];
*/
// return ncr(2*n,n)/(n+1);
long ans=1;
for(int i=0; i<n; i++)
ans*= (4*i+2)/(i+2.);
return ans;
}
long ncr(int n, int r)
{
long ans=1;
for(int i=0; i<r; i++)
{
ans*=(n-i);
ans/=(i+1);
}
return ans;
}
vector<int> memo;
int countbst(int n)
{
if(n==0 or n==1)
return memo[n]=1;
if(memo[n]!=-1)
return memo[n];
int cnt=0;
for(int i=1; i<=n; i++)
cnt+= countbst(i-1)*countbst(n-i);
return memo[n]=cnt;
}
};
//GFG -------------------
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
const int mod = 1e9+7;
public:
//Function to return the total number of possible unique BST.
int numTrees(int n)
{
vector<long> dp(n+1);
dp[0]=1; // one bst with zero node, empty bst
dp[1]=1; // one bst with one node, structurally unqiue;
// for each node in root index, number of bst in left subtree * number of bst in right subtree
for(int root=2; root<=n; root++)
{
for(int left=1; left<=root; left++)
dp[root] = (dp[root] + ((dp[left-1]%mod)*(dp[root-left]%mod))%mod)%mod;
}
return dp[n]%mod;
}
};
//{ Driver Code Starts.
#define mod (int)(1e9+7)
int main(){
//taking total testcases
int t;
cin>>t;
while(t--){
//taking total number of elements
int n;
cin>>n;
Solution ob;
//calling function numTrees()
cout<<ob.numTrees(n)<<"\n";
}
}
// } Driver Code Ends