File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
24 - Dynamic Programming Problems/28 - Unique Binary Search Trees Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Helper function to calculate the number of unique BSTs for 'n' nodes using memoization.
4+ int solve (int n, vector<int >& dp) {
5+ // Base case: If there are 0 or 1 nodes, there is only 1 unique BST possible.
6+ if (n <= 1 ) return 1 ;
7+
8+ // Check if the result for 'n' is already computed and stored in dp.
9+ if (dp[n] != -1 ) return dp[n];
10+
11+ int ans = 0 ; // Initialize the variable to store the total number of unique BSTs.
12+
13+ // Loop through each number i from 1 to n.
14+ // Treat 'i' as the root of the BST.
15+ for (int i = 1 ; i <= n; i++) {
16+ // Recursively calculate the number of unique BSTs for the left and right subtrees.
17+ // Left subtree has (i-1) nodes.
18+ // Right subtree has (n-i) nodes.
19+ ans += solve (i-1 , dp) * solve (n-i, dp);
20+ }
21+
22+ // Store the computed result for 'n' in the dp array for future use.
23+ return dp[n] = ans;
24+ }
25+
26+ // Main function to calculate the number of unique BSTs for 'n' nodes.
27+ int numTrees (int n) {
28+ // Create a dp array initialized with -1 to indicate uncomputed results.
29+ vector<int > dp (n+1 , -1 );
30+
31+ // Call the helper function with the initial value of 'n' and the dp array.
32+ return solve (n, dp);
33+ }
34+ };
You can’t perform that action at this time.
0 commit comments