Leecode 0096. Unique Binary Search Trees
96. Unique Binary Search Trees
Given an integer n
, return *the number of structurally unique **BST'*s (binary search trees) which has exactly n
nodes of unique values from 1
to n
.
Example 1:
1 | Input: n = 3 |
Example 2:
1 | Input: n = 1 |
题目大意
给定一个整数 n
,计算由 1
到 n
为节点所组成的结构独特的二叉搜索树(BST)的数量。
例如:
- 输入
n = 3
,存在 5 种结构独特的 BST,返回5
; - 输入
n = 1
,只有 1 种 BST,返回1
。
解题思路
计算独特 BST 的数量可以通过动态规划(DP) 实现,核心思路基于以下观察:
- 若选择
i
作为根节点,则左子树由1~i-1
构成,右子树由i+1~n
构成; - 左子树的独特结构数量为
dp[i-1]
,右子树的独特结构数量为dp[n-i]
(右子树可视为1~n-i
的结构映射); - 以
i
为根的 BST 数量为左、右子树数量的乘积; - 总数量为所有可能根节点的数量之和。
动态规划递推公式:
dp[0] = 1
(空树视为 1 种结构)dp[n] = Σ (dp[i-1] * dp[n-i])
,其中i
从 1 到 n
代码实现
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.