您的位置:首页 > 产品设计 > UI/UE

LeetCode(94)Unique Binary Search Trees

2014-01-11 15:38 148 查看
题目如下:

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个树。那么只考察BST的root的取值的可能性,有n个。假设BST的root为i,则以i为root的BST的总数量为取决于它的左子树和右子树,具体说来,是左子树的数量和右子树的数量的乘积。那么左子树的数量有多少个呢?右子树的数量有多少个呢?这个问题和刚才的问题完全一样,所以这样就构成了递归。

base case是,当n=0或者n=1时,显然BST数量只能有1个。

我的代码:

//68ms过大集合
class Solution {
public:
    int numTrees(int n) {
        if(n==1||n==0)
            return 1;
        else {
            int sum=0;
            for(int i=1;i<=n;i++){
                sum += numTrees(i-1)*numTrees(n-i);
            }
            return sum;
        }
    }
};


小结如下:

(1) 本题的核心是卡特兰数的问题,卡特兰数问题还有很多,比如LeetCode中有一个括号问题,其本质也是卡特兰数问题,现在理解还不太透彻,稍后对卡特兰数问题作总结。

(2) 再次发现递归的用处了,以后脑袋不好考虑的问题都可以要想想是否可以用递归来试试,正好也发挥一下机器和人相比的优势。

update: 2014-10-06

把递归改为迭代,用空间换时间,可以减少一部分运行时间。

class Solution {
public:
    int numTrees(int n) {
        int* sum = new int[n+1];
        memset(sum, 0, sizeof(int) *(n+1));  //给这片空间赋初始值
        sum[0] = 1;
        for(int i = 1; i<= n; ++i) {
             for(int j = 0; j <= i -1; ++j) {
                 sum[i] += sum[j] * sum[i -j -1];
             }
        }
        return sum
;
    }
};


update: 2015-03-23

1. 现在递归提交已经是TLE了。

2. 初始化数组的一个更加简洁的表达方式是:

int* array = new int[n + 1](); //()运算符起到初始化作用,代替了memeset(array, 0, sizeof(int) *(n + 1));


代码如下:

//2ms
class Solution {
public:
int numTrees(int n) {
int* array = new int[n + 1](); //()运算符起到初始化作用,代替了memeset(array, 0, sizeof(int) *(n + 1));
array[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
array[i]+=array[j] * array[i - j - 1];
}
}
int result = array
;
delete [] array;
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: