- We have base conditions of
dp[0] = dp[1] = 1.
- Then we calculate result for each number of nodes
i
from2...n.
- For
i
nodes. we can consider each of the nodej
from1...i
as the root node. - Considering the jth node as the root node in BST having total of
i
nodes, the result is summation for allj
from1...i
ofdp[j-1] * dp[i-j]
. (Comparing to above solutiondp[j-1] = numTrees(j-1) and dp[i-j]=numTrees(i-j)
)
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1);
dp[0] = dp[1] = 1;
for(int i = 2; i <= n; i++)
for(int j = 1; j <= i; j++)
dp[i] += dp[j-1] * dp[i-j];
return dp[n];
}
};
- There are a few ways to solve this problem. I have explained all the solutions and approach to optimize it from Brute-Force to Dynamic Programming to solving using Catalan formula in: ✅ Simple Solution w/ Explanation | Optimization from Brute-Force to DP
- Brute-Force
( Time: O(3^N), Space: O(N) )
- Dynamic Programming - Memoization
( Time: O(N^2), Space: O(N) )
- Dynamic Programming - Tabulation
( Time: O(N^2), Space: O(N) )
- Catalan Numbers
( Time: O(N), Space: O(1) )
- Catalan Numbers (2nd Approach)
( Time: O(N), Space: O(1) )