中山大学算法课程题目详解(第十四周)
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 ; }
相关文章推荐
- 中山大学算法课程题目详解(第六周)
- 中山大学算法课程题目详解(第十六周)
- 中山大学算法课程题目详解(第十八周)
- 中山大学算法课程题目详解(第五周)
- 中山大学算法课程题目详解(第十七周)
- 中山大学算法课程题目详解(第十九周)NP问题
- 中山大学算法课程题目详解(第一周)
- 中山大学算法课程题目详解(第三周)
- 中山大学算法课程题目详解(第十三周)
- 中山大学算法课程题目详解(第十周)
- 中山大学算法课程题目详解(第十一周)
- 中山大学算法课程题目详解(第七周)
- 中山大学算法课程题目详解(第十二周)
- 中山大学算法课程题目详解(第四周)
- 中山大学算法课程题目详解(第十五周)
- 算法分析与设计课程作业第十四周#1#2#3
- 精选微软经典的算法面试100题(第1-20题) -代码详解(题目选自“结构之法”大侠的博客,答案都是本菜鸟自己做的)
- 【python数据挖掘课程】二十.KNN最近邻分类算法分析详解及平衡秤TXT数据集读取
- 【python】【leetcode】【算法题目7—Reverse Integer】
- 【第十四周 项目1(2)—验证分块查找算法】