原题:
Given n, how many structurally uniqueBST's (binary search trees) that store values 1...n?
=>给一个数n,由1~n组成的有多少种二叉搜索树。
For example,
Given n = 3, there are a total of 5 unique BST's.
=>例如:
若是n=3,就有下面5种组合。
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution {
public:
int numTrees(int n) {
}
};
晓东分析
首先我们需要知道什么是二叉搜索树,比较简单的理解,就是左子树的值都比根节点小,右子树的值都比根节点的值大。这样一来我们的思路就比较清晰了,1~n这些数都是有可能成为根节点的,假设根节点是i,那么左子树的内容就是比i小的值,也就是1~i-1,右子数的内容就是i+1~n组成的二叉搜索数。那总共的组合数就是1~i-1的组合数乘以i+1~n的组合数。事实上,i+1~n的组合数和1~n-i的组合数是一样的。这样的思路很简单吧,唯一需要注意的是当左/右子数的数目为0的时候,他不是0中组合而是1种组合(用于乘)。
代码实现:
class Solution {
public:
int numTrees(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
int i = 0;
int result = 0;
for(i = 2; i < n; i++)
result += numTrees(i - 1) * numTrees(n - i);
return result + 2 * numTrees(n - 1);
}
};
运行结果:
14 / 14 test cases passed.
| Status: Accepted |
Runtime:4 ms
|
总得来说,运行时间还是可以的。
若您有更好的算法,请提出大家共同讨论,谢谢~~