[leetcode] Unique Binary Search Trees @ Python

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
题目大意很简单,就是计算有多少个不同的二叉寻找树满足前序遍历是1,2,3...n的条件
思路:每一棵树都是由根节点,左子树,右子树构成,一旦确定根节点是x的同时,
左子树只能由1,2,3...x-1构成,同理右子树由x+1,x+2...n构成,可以
[方法1]跌代求解;

class Solution:
    # @return an integer
    def numTrees(self, n):
        dp = [1, 1, 2]
        if n < 3: return dp[n]
        dp += [0 for i in range(n-2)]
        for i in range(3, n+1):
            for j in range(i):
                dp[i] += dp[j]*dp[i-j-1]
        return dp[n]
[方法2]递归求解
class Solution:
    # @return an integer
    def numTrees(self, n):
        dp = [1, 1, 2]
        if n < 3: return dp[n]
        ans = 0  
        for i in range(n):  
            ans += self.numTrees(i)*self.numTrees(n-i-1)  
        return ans

 

posted on 2014-10-15 22:50  AIDasr  阅读(655)  评论(0编辑  收藏  举报

导航