• [LeetCode系列]卡特兰数(Catalan Number) 在求解独特二叉搜寻树(Unique Binary Search Tree)中的应用分析


    本文原题: LeetCode.

    给定 n, 求解独特二叉搜寻树 (binary search trees) 的个数.

    什么是二叉搜寻树?

    二叉查找树(Binary Search Tree),或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树

    举个栗子,
    给定 n = 3, 共有 5 个.

       1         3     3      2      1
               /     /      /       
         3     2     1      1   3      2
        /     /                        
       2     1         2                 3

     

    本题的解题思路如下:

    设n对应的BST个数为h(n), n-1对应的个数为h(n-1)...依此类推.

    那么,

    • 把1放在根节点, 2...n放在右侧, 总种类是h(1) * h(n-1)
    • 把2放在根节点, 1放在左侧, 3...n放在右侧, 总种类是h(2) * h(n-2)
    • ....
    • 把n放在根节点, 1...n-1放在左侧, 总种类是h(n-1) * h(1)

    所以h(n) = h(1) * h(n-1) + h(2) * h(n-2) +...+ h(n-2) * h(2) + h(n-1) * h(1)

    上述h(n)表达式即为卡特兰数.(幽兰止水的CSDN博客)

     

    下面是实现的C++代码:

     1 class Solution {
     2 public:
     3     int numTrees(int n) {
     4         if (n < 0) return 0;
     5         vector<int> h(n+1, 0);
     6         h[0] = 1;
     7     
     8         for(int i = 1; i <= n; i++) 
     9             for (int j = 0; j < i; j++) 
    10                 h[i] += h[j] * h[i-j-1];
    11     
    12         return h[n];
    13     }
    14 };

     

    对于此代码本人有一个疑惑, 就是为何h(n) = h(0) * h(n-1) +... 而不是h(n) = h(1) * h(n-1) +... 呢?

  • 相关阅读:
    国庆·生日
    国足
    Eason's concert
    今天的斩获
    The 4400
    闷热
    24
    一直登录不了。。。原来是因为。。。
    黄色暴雨警告
    绝密飞行
  • 原文地址:https://www.cnblogs.com/lancelod/p/3849390.html
Copyright © 2020-2023  润新知