Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
求出N个节点二叉搜索树的所有形态的个数~可以用动态规划来做,选取一个结点为根,以这个结点为根的可行二叉树数量就是左右子树可行二叉树数量的乘积,所以总的数量是将以所有结点为根的可行结果累加起来~下面dp[i]表示含有i个节点的二叉查找树的数量~这种解法时间复杂度为O(n^2)
class Solution:
# @return an integer
def numTrees(self, n):
if n <= 0: return 0
dp = [0 for i in xrange(n + 1)]
dp[0], dp[1] = 1, 1
for i in xrange(2, n + 1):
for j in xrange(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[n]