96. Unique Binary Search Trees
# Medium

Solution:
Initialize
dp[n+1]
,dp[0]=1
. Think about how to computed[i]
and the value ofdp[1]
should be.Move root until
ith
, sum all of the possible roots, then getdp[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 = , space complexity =
Last updated
Was this helpful?