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
其实很容易想到,对于一个根结点,所有情况是左子树个数与右子树个数的乘积,而对于n个结点,所有情况为对于每一个结点作为根时的情况的和。一开始直接写了一段递归,明知道过不了大集合还是试了一下,结果小集合也没有过,所以干脆bottom-up吧。代码:
1 int numTrees(int n) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int* cache = (int*)malloc(sizeof(int)*(n+1)); 5 int i,j,sum; 6 cache[0]=1; 7 cache[1]=1; 8 //printf("%d ",cache[0]); 9 for(i=2;i<=n;i++){ 10 sum=0; 11 for(j=0;j<i;j++) 12 sum+=cache[j]*cache[i-1-j]; 13 cache[i]=sum; 14 //printf("%d ",cache[i]); 15 } 16 int result = cache[n]; 17 free(cache); 18 return result; 19 }