zoukankan      html  css  js  c++  java
  • LeetCode96:Unique Binary Search Trees

    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
    给定一个数n,求1到n这些数能够构成多少棵二叉树。

    给定一个序列1.....n,为了构造全部二叉树。我们能够使用1......n中的每个数i作为根节点,自然1......(i-1)必定位于树的左子树中。(i+1).....n位于树的右子树中。然后能够递归来构建左右子树。因为根节点是唯一的。所以能够保证构建的二叉树都是唯一的。

    使用两个状态来记录:

    G(n):长度为n的序列的全部唯一的二叉树。

    F(i,n),1<=i<=n:以i作为根节点的二叉树的数量。

    G(n)就是我们要求解的答案。G(n)能够由F(i,n)计算而来。

    G(n)=F(1,n)+F(2,n)+...+F(n,n)                      (1)

    G(0)=1,G(1)=1

    对于给定的一个序列1.....n。我们取i作为它的根节点。那么以i作为根节点的二叉树的数量F(i)能够由以下的公式计算而来:

    F(i,n)=G(i-1)*G(n-i) 1<=i<=n                         (2)

    综合公式(1)和公式(2),能够看出:

    G(n) = G(0) * G(n-1) + G(1) * G(n-2) + … + G(n-1) * G(0)

    这就是上面这个问题的答案。

    參考自:https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i

    能够看出这个问题和斐波拉也数列一样既能够用递归求解。也不能够不用递归求解,可是在leetcode中使用递归求解会显示超时。可是运行结果还是正确的。


    解法一:递归解法

    runtime:0ms

    class Solution {
    public:   
         int numTrees(int n) {
            if(n==0||n==1)
                return 1;
            
            int result=0;
            for(int i=0;i<n;i++)
                result+=numTrees(i)*numTrees(n-i-1);
                
            return result;
         }
        
    };


    解法二:非递归解法

    class Solution {
    public:
        int numTrees(int n) {
            int *G=new int[n+1]();
            G[0]=1;
            G[1]=1;
            for(int i=2;i<=n;i++)
            {
                for(int j=0;j<i;j++)
                    G[i]+=G[j]*G[i-j-1];
            }
            return G[n];
        }
    };

    解法三:数学公式

    数学上有一个卡塔兰数(Catalan):

    令h(0)=1,h(1)=1,卡塔兰数数满足递归式:

    h(n)= h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) (当中n>=2),这是n阶递归关系;
    该递推关系的解为:h(n)=C(2n,n)/(n+1)=P(2n,n)/(n+1)!=(2n)!/(n!*(n+1)!) (n=1,2,3,...)
    所以能够直接使用这个递归公式进行求解:
    class Solution {
    public:
         int numTrees(int n) {
            long long ans=1;
            for(int i=n+1;i<=2*n;i++)
            {
                ans=ans*i/(i-n);
            }
            return ans/(n+1);
             
         }
    
    };


  • 相关阅读:
    verilog 基础知识
    excel函数提取身份证出生日期,分离日期时间的日期和时间
    excel函数提取内容中的汉字
    excel匹配函数vlookup和lookup
    excel计数函数COUNTIF、COUNTIFS
    excel函数sum、sumif和sumifs
    excel替换函数substitute
    excel判断数据是否存在另一列中
    python用random模块模拟抽奖逻辑(print修改end参数使打印结果不分行)
    excel用函数去掉单元格内容中的括号,并只保留单元格里面的内容
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6785005.html
Copyright © 2011-2022 走看看