catlan数:
递归的方法:
class Solution {
public:
int numTrees(int n) {
if(n==1||n==0) return 1;
int num=0;
for(int i=1;i<=n;i++)
num+=numTrees(i-1)*numTrees(n-i);
return num;
}
};
动态规划方法(网上的):
class Solution {
public:
int numTrees(int n) {
if(n <= 1) return n;
int *ways = new int[n + 1];
ways[0] = 1;
ways[1] = 1;
for(int i = 2 ; i <= n; ++i) {
ways[i] = 0;
for(int left = 0; left < i; ++ left) {
//with number of left noeds in the left sub-tree
int lways = ways[left];
int rways = ways[i - left - 1];
ways[i] += lways * rways;
}
}
int ret = ways[n];
delete [] ways;
return ret;
}
};
诗辉的解法(DP):