标签:
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
int numTrees(int n) { int *result = malloc((n + 1)* sizeof(int)); if(n == 0 || n == 1) return 1; if(n == 2) return 2; result[0] = result[1] = 1; result[2] = 2; for(int i = 3; i <= n; i++) { int tmp = 0; result[i] = 0; for(int j = 1; j <= i / 2; j++) tmp += result[j - 1] * result[i - j]; result[i] = tmp * 2; if(i - (i / 2) * 2) result[i] += result[i / 2] * result[i / 2]; } return result[n]; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/5037116.html