File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
24 - Dynamic Programming Problems/28 - Unique Binary Search Trees Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the number of unique BSTs for 'n' nodes using a bottom-up approach.
4+ int solve (int n) {
5+ // Create a dp array of size (n+1) to store the results for subproblems.
6+ // dp[i] will hold the number of unique BSTs that can be formed with 'i' nodes.
7+ vector<int > dp (n+1 , 0 );
8+
9+ // Base cases:
10+ // When there are 0 nodes, there is 1 unique BST (an empty tree).
11+ // When there is 1 node, there is 1 unique BST (the single node as the root).
12+ dp[0 ] = dp[1 ] = 1 ;
13+
14+ // Fill the dp array for all values from 2 to n (Bottom-Up approach).
15+ for (int i = 2 ; i <= n; i++) {
16+ // Calculate the number of unique BSTs for 'i' nodes.
17+ for (int j = 1 ; j <= i; j++) {
18+ // Treat 'j' as the root node.
19+ // The left subtree has (j-1) nodes.
20+ // The right subtree has (i-j) nodes.
21+ dp[i] += dp[j-1 ] * dp[i-j];
22+ }
23+ }
24+
25+ // Return the result for 'n' nodes.
26+ return dp[n];
27+ }
28+
29+ // Main function to calculate the number of unique BSTs for 'n' nodes.
30+ int numTrees (int n) {
31+ return solve (n); // Call the helper function with the input 'n'.
32+ }
33+ };
You can’t perform that action at this time.
0 commit comments