Unique Binary Search Trees
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
int numTrees(int n) { int *result = malloc((n + 1)* sizeof(int)); if(n == 0 || n == 1) return 1; if(n == 2) return 2; result[0] = result[1] = 1; result[2] = 2; for(int i = 3; i <= n; i++) { int tmp = 0; result[i] = 0; for(int j = 1; j <= i / 2; j++) tmp += result[j - 1] * result[i - j]; result[i] = tmp * 2; if(i - (i / 2) * 2) result[i] += result[i / 2] * result[i / 2]; } return result[n]; }
- 选择序列中一个值为根节点,左子树和右子树,分别可以有剩余个数排列的乘积
- 因为中间左右两边选择的个数相同,可以分开两边计算
- 开辟空间时,需要开辟n+1个,和数组的[n]对应