您的位置:首页 > 产品设计 > UI/UE

[Leetcode]Unique Binary Search Trees

2015-01-19 22:38 363 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python