96. Unique Binary Search Trees
Tags:
Medium
Skills:
Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Cho một số nguyên dương n, hãy tính số lượng cấu trúc BST khác nhau có thể tạo ra từ các số nguyên từ 1 đến n, mối số sử dụng đúng 1 lần
Hiểu về BST
Approach
Nhận xét

DP
Time and space complexity
Solution
1function numTrees(n: number): number {
2 const dp: number[] = new Array(n + 1).fill(0);
3 dp[0] = 1;
4 dp[1] = 1;
5 for(let nodes = 2; nodes <= n; nodes++) {
6 for(let root = 1; root <= nodes; root++) {
7 const left = root - 1;
8 const right = nodes - root;
9 dp[nodes] += dp[left] * dp[right];
10 }
11 }
12
13 return dp[n]
14};