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
How Many Binary Trees Are There?
There are five distinct shapes of binary trees with three nodes:
But how many are there for n nodes?
Let C(n) be the number of distinct binary trees with n nodes. This is equal to the number of trees that have a root, a left subtree with j nodes, and a right subtree of (n-1)-j nodes, for each j. That is,
C(n) = C(0)C(n-1) + C(1)C(n-2) + ... + C(n-1)C(0)
which is
The first few terms:
C(0) = 1 C(1) = C(0)C(0) = 1 C(2) = C(0)C(1) + C(1)C(0) = 2 C(3) = C(0)C(2) + C(1)C(1) + C(2)C(0) = 5 C(4) = C(0)C(3) + C(1)C(2) + C(2)C(1) + C(3)C(0) = 14
You can prove
Here's the number of 8-node binary trees:
1 16! 16×15×14×13×12×11×10 C(8) = - × ---- = -------------------- = 13×11×10 = 1430 9 8!8! 8×7×6×5×4×3×2×1
Also see Wikipedia's article on the Catalan Numbers.
Solution1:
通过以上分析可用DP解决。
public int numTrees(int n) {
if(n<=1) return 1;
int[] c = new int[n+1];
c[0]=c[1]=1;
for(int i=2; i<=n; i++) {
for(int j=0; j<i; j++) {
c[i] += c[j]*c[i-j-1];
}
}
return c[n];
}
Solution2:
根据Catalan Number的Fourth Proof,
那么,
(4n-2)Cn-1 = (n+1)Cn,
也就是:
Cn = Cn-1(4n-2)/(n+1)
public int numTrees(int n) {
if(n<=1) return 1;
int res = 1;
for(int i=1; i<=n; i++) {
res = res*(4*i-2)/(i+1);
}
return res;
}