码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] Unique Binary Search Trees @ Python

时间:2014-10-16 00:30:31      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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

 

[leetcode] Unique Binary Search Trees @ Python

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/asrman/p/4027651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!