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
动态规划。 研究了一下,貌似可以归类为数学上的卡塔兰数,公式是 A(n) = A(0) * A(n-1) + A(1) *A(n-2) + ... + A(n-1) * A(0). 初始条件A(0) = 1, A(1) = 1
每一个n的情况,取决于所有从0到n-1的 n种情况的集合。
class Solution:
# @return an integer
def numTrees(self, n):
# Algorithm: 0-->1, 1-->1, A(n) = A(0) * A(n-1) + A(1) + A(n-2) + ... + A(n-1) * A(0)
dp = [ 0 for i in xrange(n+1) ]
dp[0] = dp[1] = 1
for nodeNum in xrange(2,n+1):
for leftSubNum in xrange(nodeNum):
dp[nodeNum] += dp[leftSubNum] * dp[nodeNum - 1 - leftSubNum]
return dp[n]