File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
24 - Dynamic Programming Problems/28 - Unique Binary Search Trees Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the nth Catalan number using a mathematical formula.
4+ int solve (int n) {
5+ // Initialize a variable to store the computed Catalan number.
6+ // Using 'long long' to handle intermediate results that might exceed int limits.
7+ long long catalan = 1 ;
8+
9+ // Compute the value of (2n)! / n! in a loop.
10+ // This is a part of the Catalan number formula: C(n) = (2n)! / ((n+1)! * n!).
11+ for (int i = 0 ; i < n; i++) {
12+ // Update 'catalan' using the current term of the formula.
13+ // Multiply by (2n - i) and divide by (i + 1) iteratively.
14+ catalan = catalan * (2 * n - i) / (i + 1 );
15+ }
16+
17+ // Divide the computed value by (n + 1) to complete the Catalan number calculation.
18+ return catalan / (n + 1 );
19+ }
20+
21+ // Main function to calculate the number of unique BSTs for 'n' nodes.
22+ int numTrees (int n) {
23+ // Call the helper function 'solve' to compute the nth Catalan number.
24+ return solve (n);
25+ }
26+ };
You can’t perform that action at this time.
0 commit comments