题目:
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.
思路:
当n = 1 时 BST的个数是1;
当n = 2 时 BST的个数是2;
当n = 3 时 BST的个数是5;
规律是:
代码如下:
public class Solution {
public int numTrees(int n) {
if (n <= 2) {
return n;
}
if (n == 3) {
return 5;
}
int[] nums = new int[n + 1];
nums[0] = 0;
nums[1] = 1;
nums[2] = 2;
nums[3] = 5;
for (int i = 4; i <= n; i++) {
int sum = 0;
for (int j = 1; j < i-1; j++) {
sum = sum + nums[j] * nums[i-j-1];
}
nums[i] = sum + 2 * nums[i-1];
}
return nums[n];
}
}