# 96. Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
# Solution
Approach 1: DP, e.g., use a table to prestore previously computed results. Time: O(N^2)
.
# Code (Python)
Approach 1:
def numTrees(self, n: 'int') -> 'int':
# naive recursion
#if n == 0:
# return 1
#if n == 1:
# return 1
#total = 0
#for i in range(n):
# total += self.numTrees(i) * self.numTrees(n - 1 - i)
#return total
# dp: O(N^2)
nums = [0 for _ in range(n + 1)]
nums[0], nums[1] = 1, 1
for i in range(2, n + 1):
for j in range(i):
nums[i] += nums[j] * nums[i - 1 - j]
return nums[-1]
# Code (C++)
Approach 1:
class Solution {
public:
int numTrees(int n) {
int treeNum[n+1] = {0};
treeNum[0] = 1;
for (int len = 1; len <= n; ++len)
{
for (int root = 1; root <= len; ++root)
{
int leftLen = root - 1;
int rightLen = len - root;
treeNum[len] += treeNum[leftLen] * treeNum[rightLen];
}
}
return treeNum[n];
}
};