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个数中任何一个数都可以当成根节点,左边j个结点,右边n-j-1个
所以就有nums[n] = nums[0]*nums[n - 1]+nums[1 ]*nums[n- 2]+nums[2]*nums[n- 3]+...+nums[n-1]*nums[0]; 因此我们需要先求出nums[0]--nums[n-1] 最后返回nums[n]即可
class Solution {
public int numTrees(int n) {
int[] arr = new int[n + 1];
arr[0] = arr[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++)
arr[i] += arr[j] * arr[i - j - 1];
}
return arr[n];
}
}