题目描述:
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
解题思路:
动态规划法。
用G(n)表示长度为n组成的二叉搜索树的数目;
G(0) = 1, G(1) = 1
F(i,n)表示以i为根节点,长度为n组成的二叉搜索树的数目。
从而G(n) = F(1,n) + F(2,n) + ...+ F(n,n)
而F(i,n) = G(i - 1) * G(n - i) 1<=i <=n
从而G(n) = G(0) * G(n - 1) + G(1) * G(n - 2) + ... + G(n - 1) * G(0)
代码如下:
public class Solution{ public int numTrees(int n){ int[] res = new int[n + 1]; res[0] = res[1] = 1; for(int i = 2; i <= n; i++){ for(int j = 0; j <= i - 1; j++){ res[i] += res[j] * res[i - 1 - j]; } } return res[n]; } }