Unique Binary Search Trees
Given an integer n, return the number of structurally unique BSTs (binary search trees) which have exactly n nodes of unique values from 1 to n.
Examples
Input: 3
Output: 5
Input: 1
Output: 1
Hints
Consider the recursive nature of the problem: For any root value `i` (1 ≤ i ≤ n), the left subtree will contain values `1` to `i-1` and the right subtree will contain values `i+1` to `n`. The total number of unique BSTs is the sum of all possible combinations of left and right subtrees for each root.
Observe that the solution follows the Catalan number sequence, where `G(n) = sum(G(i-1) * G(n-i))` for `i` from `1` to `n`. This recurrence relation can be computed using dynamic programming to avoid redundant calculations.
Implement a bottom-up dynamic programming approach where `dp[n]` is computed iteratively from `dp[0]` to `dp[n]`. For each `n`, calculate `dp[n]` as the sum of `dp[i] * dp[n-1-i]` for all `i` from `0` to `n-1`, leveraging previously computed values to build the solution efficiently.
Unique Binary Search Trees
Given an integer `n`, return the number of structurally unique BSTs (binary search trees) which have exactly `n` nodes of unique values from `1` to `n`.