题目
给定一个整数 n,求以 1 … n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees
分治+memo
直接套用了之前的的题95的方式来做。
即[start, end]能构造的树的种类——所以有i = range {start, end}分别做根,得到的树的种类之和。但是还是没能直接想出来,看了答案才得到启发的。
class Solution {
public:
int numTrees(int n) {
if(!n || n == 1)
return 1;
vector<vector<int>> memo(n+2, vector<int>(n+2, 0));
return numTrees(1, n+1, memo);
}
int numTrees(int start, int end, vector<vector<int>> &memo)
{
if(!memo[start][end])
{
int ret = 0;
for(int i = start; i < end; i++)
{
int left = numTrees(start, i, memo);
int right = numTrees(i+1, end, memo);
ret += left * right;
}
memo[start][end] = ret;
if(!ret)
memo[start][end] = 1;
}
return memo[start][end];
}
};