Skip to content

Commit edac295

Browse files
authored
Create 04 - Catalan Number Approach.cpp
1 parent 9625959 commit edac295

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
};

0 commit comments

Comments
 (0)