Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?
Example:
Input: 3 Output: 5 Explanation: 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个结点,除去根节点,还剩余n-1个结点。n个节点中每一个节点都可以用来做根节点
因此左右子树的结点数分配方式如下所示:
(0,n-1), (1,n-2), (2, n-3), ....(n-1,0)
我们可以简单的得到:
n=0时,种类数为dp(n)=1;
n=1时,种类数为dp(n)=1;
则可以依次计算得到n个结点时二叉树的种类。
即:dp(n)=dp(0)*dp(n-1)+dp(1)*dp(n-2)+dp(2)*dp(n-3)+...+dp(n-1)*dp(0)
public int numTrees(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= n; i++){
for(int j = 0; j < i ; j++){
dp[i] += dp[j] * dp[i - j - 1];
}
}
return dp[n];
}