File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed
24 - Dynamic Programming Problems/28 - Unique Binary Search Trees Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int numTrees (int n) {
4+ // Base case: If there are 0 or 1 nodes, there is only 1 unique BST possible.
5+ if (n <= 1 ) return 1 ;
6+
7+ int ans = 0 ; // Initialize the variable to store the total number of unique BSTs.
8+
9+ // Loop through each number i from 1 to n.
10+ // Treat 'i' as the root of the BST.
11+ for (int i = 1 ; i <= n; i++) {
12+ // Recursively calculate the number of unique BSTs for the left and right subtrees.
13+ // Left subtree has (i-1) nodes.
14+ // Right subtree has (n-i) nodes.
15+ ans += numTrees (i-1 ) * numTrees (n-i);
16+ }
17+
18+ // Return the total count of unique BSTs for n nodes.
19+ return ans;
20+ }
21+ };
You can’t perform that action at this time.
0 commit comments