Leetcode 96. Unique Binary Search Trees
Given an integer n, return the number of structurally unique Binary Search Trees (BSTs) that store values 1 to n.
n: What is the maximum value of n we need to consider?
n will be within the range [1, 19].int type in C++?
1 <= n <= 19.We can solve this problem using Dynamic Programming. The key insight is to use the concept of Catalan numbers, which count the number of BST configurations.
Steps:
dp where dp[i] represents the number of unique BSTs that can be formed with i nodes.dp[0] = 1 (An empty tree).dp[1] = 1 (A single node tree).i from 2 to n, compute dp[i] using previously computed values:
j from 1 to i, treat j as the root.j-1 nodes and the right subtree would have i-j nodes.dp[i] = sum(dp[j-1] * dp[i-j]) for all j in range [1, i].dp[n]: The result is stored in dp[n].#include <vector>
class Solution {
public:
int numTrees(int n) {
std::vector<int> dp(n + 1, 0);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] += dp[j - 1] * dp[i - j];
}
}
return dp[n];
}
};
n (i.e., O(n)), and the inner loop (which calculates the sum) also runs up to n (nested O(n)).dp of size n+1.This approach is efficient and manageable within the provided constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?