【LEETCODE】96-Unique Binary Search Trees

来源:互联网 发布:淘宝买家退货率高后果 编辑:程序博客网 时间:2024/06/05 23:20

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


参考:

用卡特兰数解决:南郭子綦:leetcode实现代码

http://www.cnblogs.com/zuoyuan/p/3747824.html

卡特兰数解决思路:n个节点构成的二叉树,共有多少种情形?

http://buptdtt.blog.51cto.com/2369962/832586

更详细解释

http://blog.csdn.net/vidio/article/details/6787899

扩展:从《编程之美》买票找零问题说起,娓娓道来卡特兰数——兼爬坑指南

http://www.cnblogs.com/wuyuegb2312/p/3016878.html


思路:

给 n 个节点,设要求的个数为 f(n)

则 n=0时,f(n)=1,n=1时,f(n)=1

当 n>2时,留 1个节点作为 root,那么剩下 n-1个节点,在左右子树的分配方式具有如下情形:

左       右

0        n-1

1        n-2

...

n-1      0

此时,组合的数为 f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)


class Solution(object):    def numTrees(self, n):        """        :type n: int        :rtype: int        """                dp=[1,1]                if n<=1:                               #因range(n-1) n-1>=1            return dp[n]        else:            dp += [0 for i in range(n-1)]      #为dp[i]赋初始值0                        for i in range(2,n+1):             #i=2,3,...n                for j in range(0,i):           #j=0,...n-1                    dp[i]+=dp[j]*dp[i-1-j]     #dp[n]=0+dp[0]*dp[n-1]+...+dp[n-1]*dp[0]                            return dp[n]




0 0
原创粉丝点击