不同的二叉搜索树-python
https://leetcode-cn.com/problems/unique-binary-search-trees/
思路:对于n个数,1,2,3,4,,,,i,,,n。以i为节点时,i前面的序列作为左子,i右边的作为右子树。左右子树时有顺序的,因此可以忽略具体值得大小,只需要看序列的个数。假设长度为n的序列的有F(n)种构造个数,那么以第i个节点为跟节点的时候个数为前后两个新的序列能够构造的个数的乘积。即F(i,n)=F(i-1)F(n-i),所以总个数为:$ F(n) = \sum_{i=1}^{n}{F(i-1)F(N-I)} $
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
res = [0] * (n+1)
res[0] = 1
res[1] = 1
for i in range(2, n+1):
for j in range(1, i+1):
res[i] += res[j-1]*res[i-j]
return res[-1]