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
Code:
class Solution:
def numTrees(self, n: int) -> int:
T = [1, 1, 2] + [0]*(n - 2)
for m in range(3, n + 1):
for i in range(m):
T[m] += T[i] * T[m - 1 - i]
return T[n]
def numTreesFaster(self, n):
T = [1, 1, 2] + [0]*(n - 2)
for m in range(3, n + 1):
mid, remainder = divmod(m, 2)
for i in range(mid):
T[m] += T[i] * T[m - 1 - i]
T[m] *= 2
if remainder: T[m] += T[mid] * T[mid]
return T[n]