[leetcode] 96. Unique Binary Search Trees

来源:互联网 发布:淘宝客服介入处理时间 编辑:程序博客网 时间:2024/05/01 09:22

Givenn, how many structurally uniqueBST's (binary search trees) that store values 1...n?

For example,

Givenn = 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~n共n个数,求出可能的二叉搜索树个数,题目难度为Medium。

二叉搜索树相信大家都已经非常熟悉,这里就不再详细介绍。我们知道根节点把二叉搜索树分为两部分,左子树上所有节点的值比根节点小,右子树上所有节点的值比根节点大,而且左子树和右子树也都是二叉搜索树。这样我们依次拿1~n来作为根节点,当遍历到i时,1~i-1组成了左子树(可能没有),i+1~n组成右子树(可能没有),这样问题就转换为求两个子树的二叉搜索树个数了。至此大家肯定已经想到了用动态规划的方法来解决这个问题。具体代码:

class Solution {public:    int numTrees(int n) {        vector<int> num(n+1, 0);                num[0] = 1;        for(int i=0; i<n; i++) {            for(int j=0; j<=i; j++) {                num[i+1] += num[j]*num[i-j];            }        }                return num[n];    }};
另外,组合数学中有一个常用于计数的数列叫卡特兰数(Catalan Number),可以完美解决这个问题,其递推公式为h(n)=h(n-1)*(4*n-2)/(n+1),关于卡特兰数的详细说明可以从文章结尾的传送门查看。具体代码:
class Solution {public:    int numTrees(int n) {        long long num = 1;        for(int i=1; i<=n; i++) {            num = num*(4*i-2)/(i+1);        }        return num;    }};
卡特兰数传送门:百度百科维基百科
0 0