问题描述:
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
Show Tags
Show Similar Problems
分析:这道题蛮有意思的,我当时的第一个想法是用递归找到所有的数据,但是一想只要找到总数即可,那么就得去找规律。
这个题需要使用DP算法,需要查找的数为n,那么根节点可以取的值为1,2,,,n。然后当选定了1或n时,其余值都在树的某一边,总共有多少种类呢?numTree(n-1)。但是我们已经DP了,所以为num[n-1]。与此同时,对于中间节点。比如i,那么左侧有1,2,,,i-1.右侧有i+1,i+2,,,n。所以左侧有num[i-1]种选择,右侧有num[n-i]中选择。相乘并相加得到最后结果。
时间复杂度为O(n2),空间复杂度为O(n)
代码如下:0ms
class Solution {
public:
int numTrees(int n) {
int *nums = new int[n+1]();
nums[1] = 1;
int left, right;
for (int i = 2; i <= n; i++) {
nums[i] += nums[i - 1]*2;//left edge and right edge
for (int j = 2; j < i; j++) {
left = j - 1;
right = i - j;
nums[i] += nums[left] * nums[right];
}
}
return nums[n];
}
};