Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

96. Unique Binary Search Trees 🌟🌟

Given an integer n, return the number of structurally unique BST’s (binary search trees) which has exactly n nodes of unique values from 1 to n.

MUST READ πŸ‘‡:

  1. Brute-Force                 ( Time: O(3^N), Space: O(N) )
  2. Dynamic Programming - Memoization    ( Time: O(N^2), Space: O(N) )
  3. Dynamic Programming - Tabulation     ( Time: O(N^2), Space: O(N) )
  4. Catalan Numbers             ( Time: O(N), Space: O(1) )
  5. Catalan Numbers (2nd Approach)      ( Time: O(N), Space: O(1) )

DP Solution(Tabulation)

Code

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];
    }
};