링크
n 개의 노드를 가지는 BST 개수 구하는 문제
def numTrees(self, n: int) -> int:
dp = [0] * (n+1)
dp[0] = 1
for i in range(1, n+1):
for j in range(i // 2):
dp[i] += 2 * dp[j] * dp[i- 1 - j]
if i % 2 == 1:
dp[i] += dp[i//2] ** 2
return dp[n]
def numTrees(self, n: int) -> int:
self.table = [-1] * (n+1)
self.table[0] = 1
return self.numTreesRec(n)
def numTreesRec(self, n):
if self.table[n] != -1:
return self.table[n]
total = 0
for m in range(n):
total += (self.numTreesRec(n-1-m) * self.numTreesRec(m))
self.table[n] = total
return total