[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.
求出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
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
相关文章推荐
- [C++]LeetCode: 53 Unique Binary Search Trees
- [leetcode]Unique Binary Search Trees II
- LeetCode - Unique Binary Search Trees
- LeetCode - Unique Binary Search Trees II
- [Leetcode]Unique Binary Search Trees
- [Leetcode]Unique Binary Search Trees I & II
- LeetCode(96) Unique Binary Search Trees
- leetcode 95. Unique Binary Search Trees II | Java最短代码实现
- Unique Binary Search Trees II Leetcode Python
- leetcode -- Unique Binary Search Trees II
- 【题解】【BST】【Leetcode】Unique Binary Search Trees
- leetcode 95 Unique Binary Search Trees II
- Leetcode-Unique Binary Search Trees
- 【Leetcode】Unique Binary Search Trees
- LeetCode(95) Unique Binary Search Trees II
- leetCode(26):Unique Binary Search Trees
- leetcode--Unique Binary Search Trees
- LeetCode: Unique Binary Search Trees I & II
- [Leetcode] Unique binary search trees 唯一二叉搜索树
- 95. Unique Binary Search Trees II ,leetcode