Overview
This problem is a classic application of Catalan Numbers. The number of unique BSTs with N nodes only depends on N, not on the actual values of the nodes.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an integer n, return the number of structurally unique BSTs (Binary Search Trees) which has exactly n nodes of unique values from 1 to n.
This problem is a classic application of Catalan Numbers. The number of unique BSTs with N nodes only depends on N, not on the actual values of the nodes.
If we have `N` nodes, we can pick any node `i` (from 1 to N) to be the root. Once `i` is the root, all elements `< i` go to the left subtree, and `> i` go to the right.
The number of nodes in the left subtree is `i - 1`. The number in the right subtree is `N - i`. The total combinations for root `i` is `dp[left] * dp[right]`.
We sum up these combinations for every possible root `i` from 1 to N. We build this up from `n = 2` to `N` using a bottom-up DP approach.