标签:
其实和大小没啥太大关系,主要因素是元素个数,也就是说,1,2 和 3,4 可能构成的排列组合个数是一样的,大概的思路就是这样的:
式子出来了,那代码也就出来了:
int numTrees(int n) {
vector<int> treeNumList(n + 1);
function<int(int)> getTreeNum;
getTreeNum = [&](int num)
{
if (num == 0 || num == 1){
return 1;
}
int result = 0;
if ((result = treeNumList[num]) != 0){
return result;
}
bool const isOdd = (num % 2 != 0);
const int k = isOdd? (num - 1) / 2 : num / 2;
for (int i = 0; i != k; ++i){
result += 2 * getTreeNum(i) * getTreeNum(num - i - 1);
}
if (isOdd){
result += getTreeNum(k) * getTreeNum(k);
}
treeNumList[num] = result;
return result;
};
return getTreeNum(n);
}
标签:
原文地址:http://www.cnblogs.com/wuOverflow/p/5046950.html