Unique Binary Search Trees
Givenn, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example
Note
The problem is to calculate the number of unique BST. To do so, we can define two functions:
G(n): the number of unique BST for a sequence of length
n
.F(i, n): the number of unique BST, where the number
i
is served as the root of BST (1≤i≤n).
As we can see,
G(n) is actually the desired function we need in order to solve the problem.
F(3,7) = G(2)*G(4), where [1,2] for G(2) and [4, 5, 6, 7] for G(4)
F(i, n) = G(i - 1) * G(n - i)
Summing F(i, n) ==> G(n) = ∑(G(i - 1)*G(n - i)) for 1 <= i <= n, and G(0) = G(1) = 1
Catalan number for best
C_n+1/C_n = 2(2n+1)/(n+2)
Code
Print them all - O(4^n/n^0.5)
Last updated