96. Unique Binary Search Trees Leetcode

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.

这道题考查BST的构造。 构造BST只要满足中序遍历有序即可,当array=[1,2,3,4,5,....n]时候我们可以任意选定根节点,然后求左右子树的可行子树总数。

其做法是动态规划 dp[0]=1 dp[1]=1 dp[2]=dp[0]dp[1]+dp[1]dp[0]  来源于卡特兰数的应用 http://en.wikipedia.org/wiki/Catalan_number

class Solution:
    # @return an integer
    def numTrees(self, n):
        dp=[1,1]
        if n<2:
            return dp[n]
        dp+=[0 for index in range(n-1)]
        for i in range(2,n+1):
            for j in range(i):
                dp[i]+=dp[j]*dp[i-j-1]
        return dp[n]
与这题有关系的还有构造parentheses 都是catlan number的应用。


你可能感兴趣的:(LeetCode,python,dp,BST)