# Unique Binary Search Trees

> Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

> For example,
> Given n = 3, there are a total of 5 unique BST's.

>```
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
```
>

`dp[i] = sum(dp[k] * dp[i - k -1]) 0 <= k < i`

```c++
class Solution {
public:
int numTrees(int n) {
vector dp(n + 1, 0);

//dp初始化
dp[0] = 1;
dp[1] = 1;

for(int i = 2; i <= n; i++) {
for(int j = 0; j < i; j++) {
//如果左子树的个数为j，那么右子树为i - j - 1
dp[i] += dp[j] * dp[i - j - 1];
}
}

return dp[n];
}
};
```

# Unique Binary Search Trees II

> Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

> For example,
Given n = 3, your program should return all 5 unique BST's shown below.

>```
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
```
>

```c++
class Solution {
public:
vector generateTrees(int n) {
return generate(1, n);
}

vector generate(int start, int stop){
vector vs;
if(start > stop) {
//没有子树了，返回null
vs.push_back(NULL);
return vs;
}

for(int i = start; i <= stop; i++) {
auto l = generate(start, i - 1);
auto r = generate(i + 1, stop);

//获取左子树和右子树所有排列之后，放到root为i的节点的下面
for(int j = 0; j < l.size(); j++) {
for(int k = 0; k < r.size(); k++) {
TreeNode* n = new TreeNode(i);
n->left = l[j];
n->right = r[k];
vs.push_back(n);
}
}
}

return vs;
}
};
```