Skip to content

Commit 3330db9

Browse files
Merge pull request #669 from heman1/NewAlgo
added allPossibleBST program
2 parents f8f9aa3 + 6e3e907 commit 3330db9

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/* Given an integer N, find and return the count of unique Binary search trees (BSTs)
2+
possible with nodes valued from 1 to N.
3+
Output count can be very large, so return the count modulo 10^9+7.
4+
Contraints : 1<= N <=1000
5+
Time Complexity: O(n^2)
6+
*/
7+
8+
9+
/* Recurssive solution:
10+
BSTcount(for value n) = summationOf ( BSTcount( for node [k-1]) + BSTcount( for node [n-k]) );
11+
(k)
12+
/ \
13+
/ \
14+
/ \
15+
(1 to k-1) (k+1 to n)
16+
17+
*/
18+
19+
/* Input: 3
20+
Output: 5
21+
22+
Input: 8
23+
Output: 1430
24+
*/
25+
26+
#include <bits/stdc++.h>
27+
#define mm 1000000007
28+
using namespace std;
29+
30+
int countBST(int n, int *dp) {
31+
//base condition
32+
if(n==0 || n==1)
33+
return 1;
34+
if(n==2)
35+
return 2;
36+
//if dp[n] has some value, then answer is already calculated for that n.
37+
if(dp[n]!=0) {
38+
return dp[n];
39+
}
40+
//calculating sum for every value of n.
41+
long long sum=0;
42+
for(int k=1; k<=n; k++) {
43+
sum = (sum%mm + (countBST(k-1, dp)%mm * countBST(n-k, dp))%mm)%mm;
44+
}
45+
//save the answer for n in the dp array.
46+
dp[n] = sum;
47+
return sum;
48+
}
49+
50+
51+
int main() {
52+
int n ;
53+
cin>>n;
54+
//dp array to fill in the values which are calculated (memoization).
55+
int *dp = new int[n+1] {0};
56+
cout<<countBST(n, dp);
57+
return 0;
58+
}
59+

0 commit comments

Comments
 (0)