题目源自于Leetcode。
题目: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
思路:递归思想。选出一个数k作为根节点,那么比k小的数在左子树中,比k大的数在右子树中。一共有n种选法。
方法一:递归法。
class Solution {
public:
int numTrees(int n) {
if(n==0)
return 1;
else
{
int i;
int num=0;
for(i=0;i<n;i++)
{
num += numTrees(i) * numTrees(n-i-1);
}
return num;
}
}
};
方法二:迭代法。递归法中会出现重复的计算,所以用一维动态规划法做记录。
class Solution {
public:
int numTrees(int n) {
int H[n+1];
memset(H, 0, sizeof(H));
H[0] = 1;
H[1] = 1;
for(int i=2;i<=n;i++)
for(int j=0;j<i;j++)
H[i] += H[j] * H[i-j-1];
return H[n];
}
};
注意:这个数列看起来比斐波那契数列增长的还快,所以自己写的话最好用long long类型。