Unique Binary Search Trees Algorithm
The Unique Binary Search Trees II Algorithm is an advanced algorithm that deals with the generation of structurally unique binary search trees (BSTs). This algorithm is particularly useful in solving problems that require constructing all possible BSTs given a certain number of nodes. The algorithm is based on a dynamic programming approach that recursively generates unique BSTs for a given range of sequential integers.
The algorithm starts by iterating through each integer in the given range, selecting an integer as the root node of the BST. It then constructs the left and right subtrees by recursively applying the algorithm on the range of integers smaller and larger than the root, respectively. The recursion continues until there are no more integers to be processed, at which point a null node is returned. The algorithm combines the generated left and right subtrees to form unique BST combinations with the chosen root node. Once all possible combinations of left and right subtrees are generated, they are returned as a list of unique BSTs. This process is repeated for each integer in the given range, ultimately producing a list of all possible structurally unique BSTs.
class Solution {
public:
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> dp(n + 1, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 0; j < i; j++)
dp[i] += dp[j] * dp[i-j-1];
}
return dp[n];
}
};