96. Unique Binary Search Trees
Description
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
.
Example 1:
Input: n = 3 Output: 5
Example 2:
Input: n = 1 Output: 1
Constraints:
1 <= n <= 19
Solutions
Solution 1: Dynamic Programming
We define \(f[i]\) to represent the number of binary search trees that can be generated from \([1, i]\). Initially, \(f[0] = 1\), and the answer is \(f[n]\).
We can enumerate the number of nodes \(i\), then the number of nodes in the left subtree \(j \in [0, i - 1]\), and the number of nodes in the right subtree \(k = i - j - 1\). The number of combinations of the number of nodes in the left subtree and the right subtree is \(f[j] \times f[k]\), so \(f[i] = \sum_{j = 0}^{i - 1} f[j] \times f[i - j - 1]\).
Finally, return \(f[n]\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes.
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|