Medium
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:
Input: n = 3
Output: 5
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 19
function numTrees(n: number): number {
const uniqueCount = new Array(n + 1).fill(0)
uniqueCount[0] = 1
uniqueCount[1] = 1
for (let i = 2; i <= n; ++i) {
for (let j = 1; j <= i; ++j) {
uniqueCount[i] += uniqueCount[j - 1] * uniqueCount[i - j]
}
}
return uniqueCount[n]
}
export { numTrees }