# 0095. Unique Binary Search Trees II

https://leetcode.com/problems/unique-binary-search-trees-ii

## Description

Given an integer `n`, return \*all the structurally unique \*\*BST'\*_s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg)

```
**Input:** n = 3
**Output:** [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
```

**Example 2:**

```
**Input:** n = 1
**Output:** [[1]]
```

**Constraints:**

* `1 <= n <= 8`

## ac1: divide and conquer

similar: [https://leetcode.com/submissions/detail/147072693/](https://leetcode.com/submissions/detail/147072693/)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        // Edge cases: n < 1
        if (n < 1) return new ArrayList<>();

        return generate(1, n);
    }

    private List<TreeNode> generate(int start, int end) {
        List<TreeNode> res = new ArrayList<>();
        // Exit
        if (start > end) {
            res.add(null);
        }

        // Iterate
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = generate(start, i-1);
            List<TreeNode> right = generate(i+1, end);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    res.add(new TreeNode(i, l, r));
                }
            }
        }

        return res;
    }
}
```

With cache:

```java
class Solution {
    Map<String, List<TreeNode>> cache = new HashMap<>();

    public List<TreeNode> generateTrees(int n) {
        // Edge cases: n < 1
        if (n < 1) return new ArrayList<>();

        return generate(1, n);
    }

    private List<TreeNode> generate(int start, int end) {
        if (cache.containsKey(start + "-" + end)) {
            return cache.get(start + "-" + end);
        }

        List<TreeNode> res = new ArrayList<>();
        // Exit
        if (start > end) {
            res.add(null);
        }

        // Iterate
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = generate(start, i-1);
            List<TreeNode> right = generate(i+1, end);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    res.add(new TreeNode(i, l, r));
                }
            }
        }

        cache.put(start + "-" + end, res);
        return res;
    }
}
```
