Description:
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
Note:
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
Solution:
Analysis and Thinking:
题目要求在输入n值的情况下,得出有多少种结构唯一的1~n的二叉查找树。这里我们采取了一种简便的方法,就是基于公式原理得出解,其中,我们引用catalan数公式(式子为:)。对于n个节点,将其中第j个节点设为根节点,得出左子树j-1个节点,右子树i-j个节点,左右子树相乘可得到结果。
Steps:
1.设置外层循环,用i记录,从2~n进行循环
2.设置内存循环,对于每一层i值,将j从1遍历到i
3.内循环中,将j设置为根节点,相应的左右子树分别有j-1以及i-j个节点,左右子树的种树相乘,就是当前以j为根节点得出的二叉搜索数总的数量
4.对j从1求和到j,对i从2遍历至n,得出n对于的二叉查找树数量
Codes:
class Solution {
public:
int numTrees(int n) {
vector<int> record(n + 1, 0);
record[0] = 1;
record[1] = 1;
for(int i = 2; i <= n; i++)
for(int j = 1; j <= i; j++)
{
record[i] =record[i]+record[i - j]*record[j - 1];
}
return record[n];
}
};
Results: