> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/suan-fa/shu/96-bu-tong-de-er-cha-sou-suo-shu.md).

# \[96]\[中等]\[动态规划] 不同的二叉搜索树

## 题目描述

[96. 不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees/)

给定一个整数 n，求以 1 ... n 为节点组成的二叉搜索树有多少种？

示例:

```
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
```

## 解题思路

因为题目只要求了数量, 并不需要给出具体的树结构, $$n$$个节点对应的二叉搜索树的数量是固定的. 将1到n每个数字依次作为根节点, 小于它的数字组成左子树, 大于它的数字组成右子树, 这样就能递归到左右子树各自的不同组成数量, 两者相乘, 就是在以$$i$$为根节点时, 可能的组合数量. 将1到n所有根节点对应的组合数量加在一起, 就得到了整数$$n$$对应的二叉搜索树的组成方案数量.

以上是状态转移的方案, 需要考虑的边际条件是, 当$$n$$为0或1时, 对应的组成数量都为1.

详细请参考: [不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode-solution/)

```python
class Solution:
    def numTrees(self, n: int) -> int:
        if n < 2:
            return 1

        dp = [0] * (n + 1)
        dp[0], dp[1] = 1, 1

        for i in range(2, n + 1):
            for j in range(i):
                dp[i] += dp[j] * dp[i - j - 1]
        return dp[-1]
```
