-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Day 68 】2024-01-22 - 96. 不同的二叉搜索树 #72
Comments
|
|
dp 代码class Solution {
public:
int numTrees(int n) {
vector<int> G(n + 1, 0);
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];
}
}; |
思路
G(n)的值可以通过遍历所有i,以i为根节点构造二叉搜索数,累加所有二叉搜索数的总数
对于f(i,n)则可通过左子数G(i-1)和右子数G(n-i)的所有组合方式计算得出
所以
代码 public int numTrees(int n) {
int[] G = new int[n + 1];
G[0] = 1;
G[1] = 1;
for (int m = 2; m <= n; m++) {
for (int i = 1; i <= m; i++) {
G[m] += G[i - 1] * G[m - i];
}
}
return G[n];
} 复杂度
|
class Solution:
def numTrees(self, n: int) -> int:
# 初始化数组 G 用于存储每个节点数对应的唯一BST的数量
G = [0]*(n+1)
G[0], G[1] = 1, 1 # 0个或1个节点时,只有一种唯一的BST。
# 遍历节点数从2到n
for i in range(2, n+1):
# 对于每个节点数,计算唯一BST的数量
for j in range(1, i+1):
# 以j为根节点的唯一BST数量是左子树BST数量(G[j-1])和右子树BST数量(G[i-j])的乘积。
G[i] += G[j-1] * G[i-j]
# 最终结果是n个节点时的唯一BST数量
return G[n] |
class Solution:
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
96. 不同的二叉搜索树
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/unique-binary-search-trees/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: