给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
第一次的代码:
for循环执行选每一个点作为root节点,依次将左右树的子树个数相加。
bwl={0:0,1:1,2:2}
def nT(n):
if n in bwl:
return bwl[n]
else:
count=0
for i in range(n):#选取节点
if i == n-i-1 and i==1:
count=count+nT(i)
elif i ==1 or i ==n-2:
count=count+nT(n-2)
else:
count=count+nT(i)+nT(n-i-1)
bwl[n]=count#存入备忘录
return count
return nT(n)
但是结果不对,显而易见,左右子树是不能通过相加的,而是相乘,即数的组合方式是左右子树相乘得来的。
第二次的代码:
bwl={0:0,1:1,2:2}
def nT(n):
if n in bwl:
return bwl[n]
else:
count=2*nT(n-1)#当左或右子树为0的时候
#实际上root树的个数等于nT(n-1)
for i in range(1,n-1):
count=count+nT(i)*nT(n-i-1) #左,右树的个数相乘,组合问题
bwl[n]=count#存入备忘录
return count
return nT(n)
24ms,排名91%