# Question

Formatted question description: https://leetcode.ca/all/96.html

96	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

@tag-tree


# Algorithm

Let’s first look at the situation when n = 1, only a single binary search tree can be formed. The situations where n is 1, 2, and 3 are as follows:

			1                        n = 1

2        1                   n = 2
/          \
1            2

1         3     3      2      1           n = 3
\       /     /      / \      \
3     2     1      1   3      2
/     /       \                 \
2     1         2                 3


We assign 1 when n = 0, because the empty tree is also a binary search tree, then the situation when n = 1 can be regarded as the number of left subtrees multiplied by the number of right subtrees, and the left and right subtrees Trees are all empty trees, so 1 by 1 is still 1. Then when n = 2, since both 1 and 2 can be roots, you can calculate them separately and add them together. The case of n = 2 can be calculated by the following formula (where dp[i] represents the number of BST that can be composed of i numbers):

dp[2] =

dp[0] * dp[1]
(If 1 is the root, the left subtree must not exist, and the right subtree can have a number)

+

dp[1] * dp[0]
(If 2 is the root, the left subtree can have a number, and the right subtree must not exist)


In the same way, the calculation method for n = 3 can be written:

dp[3] =
dp[0] * dp[2]
(If 1 is the root, the left subtree must not exist, and the right subtree can have two numbers)

+

dp[1] * dp[1]
(If 2 is the root, the left and right subtrees can each have a number)

+

dp[2] * dp[0]
(If 3 is the root, the left subtree can have two numbers, and the right subtree must not exist)


Java