<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:
  static vector<TreeNode*> generateTrees(const int node_count) {
    vector<vector<vector<TreeNode*>>> table(
      node_count + 1,
      vector<vector<TreeNode*>>(node_count + 1)
    );
    for (int i = 1; i <= node_count; ++i) {
      table[i][i].push_back(new TreeNode(i));
    }

    for (int width = 1; width < node_count; ++width) {
      for (int start = 1; start + width <= node_count; ++start) {
        for (TreeNode* const right_child : table[start + 1][start + width]) {
          table[start][start + width].push_back(
            new TreeNode(start, nullptr, right_child)
          );
        }
        for (TreeNode* const left_child : table[start][start + width - 1]) {
          table[start][start + width].push_back(
            new TreeNode(start + width, left_child, nullptr)
          );
        }

        for (int pos = start + 1; pos < start + width; ++pos) {
          for (TreeNode* const left_child : table[start][pos - 1]) {
            for (TreeNode* const right_child : table[pos + 1][start + width]) {
              table[start][start + width].push_back(
                new TreeNode(pos, left_child, right_child)
              );
            }
          }
        }
      }
    }
    return table[1][node_count];
  }
};
16900