Given an integer n, Seeking for 1 … n How many binary search trees are there for nodes ?
Example :
Input : 3
Output : 5
explain :
Given n = 3, Altogether 5 Binary search trees with different structures :
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
# dp[i] Express 1——i Of BST
class Solution:
def numTrees(self, n: int) -> int:
if n == 1:
return 1
dp = [0 for i in range(n+1)]
dp[0] = 1
dp[1] = 1
for i in range(2,n+1): # This cycle is f(1)+f(2)+f(3)+f(4)+...+f(i)
for j in range(1,i+1): # This loop is a calculation f(i) In the process of f(j)
dp[i] += dp[j-1] * dp[i-j]
return dp[-1]