您的位置:首页 > 其它

中山大学算法课程题目详解(第十四周)

2017-12-28 15:10 190 查看

问题描述:

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

解决思路:

第一种方法:

数字1~n 可以构成多少种二叉查找树。

从1~n中遍历选取一个点i作为树的根,则左子树的组合numTrees(left) 和右子树的组合numTrees(right)乘积即为当前根的组合数。

根据二叉查找树的定义,左子树结点个数为(i-1),右子树为(n-i)。这种方法有可能会导致Time Limit error

第二钟方法:

1. 初始化容器前两项

        result.push_back(1);

        result.push_back(1);

2. 计算含i个结点时二叉查找树的种类数,j表示1~i中取任一结点作为根。所以计算方式同递归一样,左子树(J-1)*右子树(I-J)

3. 实现递推公式,从而解决时间

   sum += (result[j-1] * result[i-j]);

4. 维护一个result的容器,容器最末尾的数即为所求F(N). 所以每次计算时需先重置0,迭代得到结果后再push进容器。

for(int i = 2; i <= n; i++)

        {

            int sum = 0;

            //计算含i个结点时二叉查找树的种类数,j表示1~i中取任一结点作为根。

            for(int j = 1; j <= i; j++)

            {

                sum += (result[j-1] * result[i-j]);   //左树*右树  实现递推公式

            }          

            result.push_back(sum);

        }


具体代码实现如下:

第一种方法:
int numTrees1(int n) {
if (n == 0 || n == 1) {
return 1;
}
else {
int ref = 0;
for (int i = 1; i <= n; i++) {
ref += (numTrees1(i - 1) * numTrees1(n - i));
}
return ref;
}
}


第二种方法:
int numTrees(int n) {
vector<int> result;
result.push_back(1);
result.push_back(1);

for (int i = 2; i <= n; i++) {
int sum = 0;
for (int j = 1; j <= i; j++) {
sum += result[j - 1] * result[i - j];
}
result.push_back(sum);
}

return result
;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: