Description:
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
Code:
1 int numTrees(int n) { 2 //f[i][j]表示数字i,i+1,...,j有多少棵不同的树 3 int f[MAX][MAX] = {0}; 4 5 for (int i = 1; i <= n; ++i) 6 {//只有一个节点的情况 7 f[i][i] = 1; 8 } 9 10 for (int i = 2; i<=n; ++i) 11 {//有2,3,4,....n个元素的情况 12 for (int j = 1; j<=n-i+1; ++j ) 13 { 14 int m = j+i-1; 15 //计算f[j][m]; 16 //先考虑两端为根节点的情况 17 f[j][m] = f[j][m-1]+f[j+1][m]; 18 for (int k = j+1; k <= m-1; ++k)//k表示以k为根节点,左边的数据为j...k-1,右边的数据为k+1,..,m 19 f[j][m] += f[j][k-1] * f[k+1][m]; 20 } 21 } 22 return f[1][n]; 23 }