Dynamic Programming. Build dp[n+1] to record how many unique BST until ith. dp[i] = sum(dp[smaller than root]*dp[greater than root]), root is changing.
Solution:
Initialize dp[n+1], dp[0]=1. Think about how to compute d[i] and the value of dp[1] should be.
Move root until ith, sum all of the possible roots, then get dp[i].
Return dp[n]
class Solution:
def numTrees(self, n: int) -> int:
# initialize dp[i], dp[i] means number of trees until i
dp = [1]*(n+1)
# regular case
for i in range(1, n+1):
num = 0
for j in range(1, i+1):
root = j
smaller = root-1
greater = i-root
num = num + dp[smaller]*dp[greater]
dp[i] = num
return dp[n]
Time complexity = O(n2) , space complexity = O(n)
mums of trees = dp[smaller than root]*dp[greater than root]