Unique Binary Search Trees

medium tree bst dp math

Problem

Given an integer n, return the number of structurally unique BSTs (binary search trees) that can store exactly n nodes with values 1..n.

Inputn = 3
Output5
G(n) = sum over root i of G(i-1) * G(n-i) — the Catalan recurrence.

def num_trees(n):
    g = [0] * (n + 1)
    g[0] = 1
    for i in range(1, n + 1):
        for j in range(1, i + 1):
            g[i] += g[j - 1] * g[i - j]
    return g[n]
function numTrees(n) {
  const g = new Array(n + 1).fill(0);
  g[0] = 1;
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= i; j++) {
      g[i] += g[j - 1] * g[i - j];
    }
  }
  return g[n];
}
class Solution {
    public int numTrees(int n) {
        int[] g = new int[n + 1];
        g[0] = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                g[i] += g[j - 1] * g[i - j];
            }
        }
        return g[n];
    }
}
int numTrees(int n) {
    vector<long> g(n + 1, 0);
    g[0] = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            g[i] += g[j - 1] * g[i - j];
        }
    }
    return (int)g[n];
}
Time: O(n²) Space: O(n)