Problem
Given an integern, return the number of structurally unique BST’s (binary search trees) which has exactly n nodes of unique values from 1 to n.
Examples
Constraints
1 <= n <= 19
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 96 with 19 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 96 # by problem number
lcpy gen -s unique_binary_search_trees # by problem name
n, return the number of structurally unique BST’s (binary search trees) which has exactly n nodes of unique values from 1 to n.
Input: n = 3
Output: 5
Input: n = 1
Output: 1
1 <= n <= 19class Solution:
# Time: O(n^2)
# Space: O(n)
def num_trees(self, n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1
for nodes in range(1, n + 1):
for left in range(nodes):
dp[nodes] += dp[left] * dp[nodes - 1 - left]
return dp[n]
| Time | Space |
|---|---|
| O(n^2) | O(n) |