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
本题使用一维线性规划解决。
如果n等于0时,结果为0;
如果n等于1时,只有一个节点,结果为1;
如果n等于2时,根节点有两种选择,结果为2;
如果n大于3时,根节点有n种选择,确定根节点后分别计算左右子树的可能情况,然后相乘就是当前根节点下所有的变形种类,之后在求和即可。算法实现如下:
1 public class UniqueBinarySearchTrees {
2 public int numTrees(int n) {
3 if (n == 1)
4 return 1;
5 if (n == 2)
6 return 2;
7 int[] record = new int[n + 1];
8 record[0] = 1;
9 record[1] = 1;
10 record[2] = 2;
11 for (int i = 3; i <= n; i++) {
12 int tmp = 0;
13 for (int k = 0; k < i; k++) {
14 tmp += (record[k] * record[i - k - 1]);
15 }
16 record[i] = tmp;
17 }
18 return record[n];
19 }
20 }