64-Unique Binary Search Trees
Total Accepted: 82788 Total
Submissions: 220611 Difficulty: Medium
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 2 3 4 5 | 6 | 7 ..........n
既然是二叉搜索树,先递增排好序,然后在序列中选定一个根,比如上图的6
然后分为左子树和右子树,这样便可以转化为子问题
设f(n)为n个数的二叉排序树的数目
则f(n) = f(0)f(n-1)+f(1)f(n-2)+.......+f(n-1)f(0)
自底向上写出公式即可
时间复杂度O(n*n),空间O(1)
效率更高可考虑直接用卡特兰公式
class Solution {
public:
int numTrees(int n) {
vector<int> f(n+1);
f[0]=1;
for(int i=1;i<=n;++i)
{
for(int k=0;k<=i-1;++k)
f[i]+=f[k]*f[i-1-k];
}
return f[n];
}
};
浙公网安备 33010602011771号