Update 0096.不同的二叉搜索树.md

This commit is contained in:
jianghongcheng
2023-06-01 22:50:49 -05:00
committed by GitHub
parent 442008bb8e
commit 41224f61bd

View File

@ -197,12 +197,13 @@ class Solution {
```python
class Solution:
def numTrees(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0], dp[1] = 1, 1
for i in range(2, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j - 1] * dp[i - j]
return dp[-1]
dp = [0] * (n + 1) # 创建一个长度为n+1的数组初始化为0
dp[0] = 1 # 当n为0时只有一种情况即空树所以dp[0] = 1
for i in range(1, n + 1): # 遍历从1到n的每个数字
for j in range(1, i + 1): # 对于每个数字i计算以i为根节点的二叉搜索树的数量
dp[i] += dp[j - 1] * dp[i - j] # 利用动态规划的思想,累加左子树和右子树的组合数量
return dp[n] # 返回以1到n为节点的二叉搜索树的总数量
```
### Go