# 不同的二叉搜索树

给你一个整数 n ,求恰由 n 个节点组成且节点值从 1n 互不相同的 二叉搜索树 有多少种?返回满足题意的二叉搜索树的种数。

 

示例 1:

输入:n = 3

输出:
5

示例 2:

输入:n = 1

输出:
1

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp ``` ## 答案 ```cpp class Solution { public: int numTrees(int n) { if (n < 1) { return 0; } return numTrees(1, n); } int numTrees(int begin, int end) { if (begin > end) { return 1; } int sum = 0; for (int i = begin; i <= end; i++) { int left = numTrees(begin, i); int right = numTrees(i + 1, end); sum += left * right; } return sum; } }; ``` ## 选项 ### A ```cpp class Solution { public: int numTrees(int n) { if (n < 2) return 1; else if (n == 3) return 5; else if (n == 4) return 14; else if (n == 5) return 42; else { int i, sum = 0, left, right; for (i = 0; i < n; i++) { left = i; right = n - i - 1; sum += numTrees(left) * numTrees(right); } return sum; } } }; ``` ### B ```cpp class Solution { public: int numTrees(int n) { if (n < 2) return 1; else { int i, sum = 0, left, right; for (i = 0; i < n; i++) { left = i; right = n - i - 1; sum += numTrees(left) * numTrees(right); } return sum; } } }; ``` ### C ```cpp class Solution { public: int numTrees(int n) { int dp[n + 1]; memset(dp, 0, sizeof(dp)); dp[0] = dp[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 0; j < i; ++j) { dp[i] += dp[j] * dp[i - j - 1]; } } return dp[n]; } }; ```