Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: ‘
分析:
参考答案解法https://leetcode.com/problems/unique-binary-search-trees/solution/
G(n)是n个数字的BST个数,注意数字是什么对结果没有影响
F(n,i)是n个数字且以第i个数字为根的BST个数。
递推公式:F(i,n)=G(i−1)⋅G(n−i)
那么从前往后可以求出G(n): G(n) = sum(G(i-1)*G(n-i))
public int numTrees(int n) {
if(n==0||n==1)
return 1;
int[] F = new int[n+1];//注意长度
F[0]=1;
F[1]=1;//注意初始化
for(int i=2;i<=n;i++){
for(int j=1;j<=i;j++){
F[i] += F[j-1]*F[i-j];
}
}
return F[n];
}