<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" style="width: 600px; height: 148px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>

class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        // dp[i] stores all unique BSTs that can be formed with i nodes
        vector<vector<TreeNode*>> dp(n + 1);
        dp[0].push_back(nullptr);  // Base case: One way to form BST with 0 nodes (empty tree)

        // Loop over the number of nodes used to construct the BSTs
        for (int totalNodes = 1; totalNodes <= n; totalNodes++) {
            // Try each node as the root, and divide the rest into left and right subtrees
            for (int rootValue = 1; rootValue <= totalNodes; rootValue++) {
                int leftSubtreeSize = rootValue - 1;
                int rightSubtreeSize = totalNodes - rootValue;

                // Generate all combinations of left and right subtrees
                for (TreeNode* leftSubtree : dp[leftSubtreeSize]) {
                    for (TreeNode* rightSubtree : dp[rightSubtreeSize]) {
                        // Create the root node and clone the right subtree with the appropriate offset
                        TreeNode* root = new TreeNode(rootValue);
                        root->left = leftSubtree;
                        root->right = cloneTreeWithOffset(rightSubtree, rootValue);
                        dp[totalNodes].push_back(root);
                    }
                }
            }
        }
        return dp[n];  // Return all unique BSTs that can be formed with n nodes
    }

private:
    // Helper function to clone the right subtree and add the offset to all node values
    TreeNode* cloneTreeWithOffset(TreeNode* originalNode, int offset) {
        if (!originalNode) return nullptr;

        TreeNode* clonedNode = new TreeNode(originalNode->val + offset);
        clonedNode->left = cloneTreeWithOffset(originalNode->left, offset);
        clonedNode->right = cloneTreeWithOffset(originalNode->right, offset);
        return clonedNode;
    }
};

17600