# 96. Unique Binary Search Trees

Given  n , how many structurally unique BST’s (binary search trees) that store values 1 …  n?

Example:

Input: 3
Output: 5
Explanation:
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


                    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


dp[2] =  dp[0] * dp[1]　　　(1为根的情况，则左子树一定不存在，右子树可以有一个数字)

+ dp[1] * dp[0]　　  (2为根的情况，则左子树可以有一个数字，右子树一定不存在)

dp[3] =  dp[0] * dp[2]　　　(1为根的情况，则左子树一定不存在，右子树可以有两个数字)

+ dp[1] * dp[1]　　  (2为根的情况，则左右子树都可以各有一个数字)

+ dp[2] * dp[0]　　  (3为根的情况，则左子树可以有两个数字，右子树一定不存在)

class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
dp[i] += dp[j] * dp[i - j - 1];
}
}
return dp[n];
}
};


class Solution {
public:
int numTrees(int n) {
long res = 1;
for (int i = n + 1; i <= 2 * n; ++i) {
res = res * i / (i - n);
}
return res / (n + 1);
}
};


Unique Binary Search Trees II

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

https://leetcode.com/problems/unique-binary-search-trees/discuss/31666/DP-Solution-in-6-lines-with-explanation.-F(i-n)-G(i-1)-*-G(n-i)

https://leetcode.com/problems/unique-binary-search-trees/discuss/31671/A-very-simple-and-straight-ans-based-on-MathCatalan-Number-O(N)-timesO(1)space

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation