给你一个整数 n
,求恰由 n
个节点组成且节点值从 1
到 n
互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。
输入:n = 3 输出:5
示例 2:
输入:n = 1 输出:1
我的思路是:枚举每一种情况,但是超时了
下面是会超时的错误示范:
class Solution {
public int numTrees(int n) {
if(n<=1){
return n;
}
return numTrees(1, n);
}
public int numTrees(int start,int end){
List<TreeNode>list=new LinkedList<>();
if(start>end){
return 1;
}
int count=0;
for(int i=start;i<=end;i++){
int leftCount = numTrees(start, i - 1);
int rightCount = numTrees(i + 1, end);
count+=leftCount*rightCount;
}
return count;
}
}
看看官方的题解:
class Solution {
public int numTrees(int n) {
int[] G = new int[n + 1];
G[0] = 1;
G[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
G[i] += G[j - 1] * G[i - j];
}
}
return G[n];
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/unique-binary-search-trees/solutions/329807/bu-tong-de-er-cha-sou-suo-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。