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
用c[i]记录i个节点的BST种类,其中C[0] = 1(空树也是一种BST),C[1] = 1。以i=3为例,如图,3个节点时的BST可以分为,左右子树一个为0一个为2的情况、左右子树一个为1另一个也为1的情况。 其中左右子树一个为0一个为2的情况实际上就有2 *C[0]*C[2]种,即排列组合中,左右子树形态各异的种类共有多少,类似的,左右子树为1的情况为C[1]*C[1],那么C[3] = C[0]*C[2] + C[1]*C[1] + C[2] * C[0]种。 用动态规划求解。
Source
public class Solution {
public int numTrees(int n) {
if(n == 0 || n == 1) return 1; //n=0时是空树,也算是一种树
int[] c = new int[n + 1];
c[0] = 1;
for(int i = 1; i <= n; i++){
for(int j = 0; j < i; j++){ //***
c[i] = c[i] + c[j] * c[i - 1 - j]; //***
}
}
return c[n];
}
}
Test
public static void main(String[] args){
System.out.println(new Solution().numTrees(3));
}