码迷,mamicode.com
首页 > 其他好文 > 详细

Unique Binary Search Trees

时间:2015-12-10 21:21:37      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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
 
int numTrees(int n) {
    int *result = malloc((n + 1)* sizeof(int));
    if(n == 0 || n == 1)
        return 1;
    if(n == 2)
        return 2;
    result[0] = result[1] = 1;
    result[2] = 2;
    for(int i = 3; i <= n; i++)
    {
        int tmp = 0;
        result[i] = 0;
        for(int j = 1; j <= i / 2; j++)
            tmp += result[j - 1] * result[i - j];
        result[i] = tmp * 2;
        if(i - (i / 2) * 2)
            result[i] += result[i / 2] * result[i / 2];
    }
    return result[n];
}
  • 选择序列中一个值为根节点,左子树和右子树,分别可以有剩余个数排列的乘积
  • 因为中间左右两边选择的个数相同,可以分开两边计算
  • 开辟空间时,需要开辟n+1个,和数组的[n]对应

Unique Binary Search Trees

标签:

原文地址:http://www.cnblogs.com/dylqt/p/5037116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!