题目:
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
题意:
这题跟95题是相关题,不过难点在于用深度优先搜索会超时,所以要换一种思路,可以用dp来解。我们只需要求出历史的小数时二叉树的种类数量,即可迭代求解大数的二叉树种类。
代码:
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 2, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
};
以上解法优于C++提交的100%代码。
题外话:
转眼,八月就过去了。如果按照学生时代,明天通常是一个新的起点。九月也意味着新的模式,和新的节奏,新一轮的努力。现在希望自己放平心态,踏踏实实把事情做好,注意身体,家人身体健康,平安,即可。愿大家一切都好。
你好,九月。