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个结点的二叉查找树有b[n]个,则设想对一个排好序的list,我们从第一个元素开始枚举根节点。对于每一个根节点,这棵二叉查找树的可能是b[left] * b[right], left < n, right < n。
故我们只需要取b[0] = 0, b[1] = 1, 然后迭代计算b[i]即可。
class Solution { public: int numTrees(int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(n == 0) return 0; int *num; num = new int[n + 1]; num[0] = 1; num[1] = 1; for(int i = 2;i <= n;i++) { num[i] = 0; for(int j = 0;j < i;j++) num[i] += num[j] * num[i - 1 - j]; } return num[n]; } };