Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
dp[i]
表示 i
个数可以组成的二叉搜索树数量。分别以 i
个数的每个数为根节点,每个数为根节点的组合数为其左子树和右子树的组合之积,所有的情况之和即为 i
个数的组合数class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1);
dp[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
};