96. Unique Binary Search Trees
题目描述
Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees
递推
思路:当构造二叉排序树时,确定了根节点之后,左右子树仍然为二叉排序树,且规模更小。故使用一个数组来记录有n个数时可构造不同的二叉排序树的个数。
int numTrees(int n){
if(n == 0)return 0;
if(n == 1)return 1;
int *f = (int*)malloc((n+1)*sizeof(int));
f[0] = 1;
f[1] = 1;
int i,j;
int sum = 0;
for(j = 2; j < n+1; j++){
for(i = 1; i < j+1; i++){
sum = sum + (f[i-1]*f[j-i]);
}
f[j] = sum;
sum = 0;
}
return f[n];
}