Skip to content

Commit b99d303

Browse files
committed
96
1 parent 7ef4192 commit b99d303

File tree

3 files changed

+66
-27
lines changed

3 files changed

+66
-27
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# [96. Unique Binary Search Trees (Medium)](https://leetcode.com/problems/unique-binary-search-trees/)
2+
3+
<p>Given <em>n</em>, how many structurally unique <strong>BST's</strong> (binary search trees) that store values 1 ...&nbsp;<em>n</em>?</p>
4+
5+
<p><strong>Example:</strong></p>
6+
7+
<pre><strong>Input:</strong> 3
8+
<strong>Output:</strong> 5
9+
<strong>Explanation:
10+
</strong>Given <em>n</em> = 3, there are a total of 5 unique BST's:
11+
12+
1 3 3 2 1
13+
\ / / / \ \
14+
3 2 1 1 3 2
15+
/ / \ \
16+
2 1 2 3
17+
</pre>
18+
19+
20+
**Related Topics**:
21+
[Dynamic Programming](https://leetcode.com/tag/dynamic-programming/), [Tree](https://leetcode.com/tag/tree/)
22+
23+
**Similar Questions**:
24+
* [Unique Binary Search Trees II (Medium)](https://leetcode.com/problems/unique-binary-search-trees-ii/)
25+
26+
## Solution 1. DP
27+
28+
Let `dp[i]` be the answer.
29+
30+
To get `dp[i]`, we can pick `j` as the root node (`1 <= j <= i`), then there are `j - 1` nodes in the left sub-tree and `i - j` nodes in the right sub-tree, and they have `dp[j - 1]` and `dp[i - j]` unique BSTs respectively. So `dp[i] = sum( dp[j - 1] * dp[i - j] | 1 <= j <= i)`
31+
32+
```cpp
33+
// OJ: https://leetcode.com/problems/unique-binary-search-trees
34+
// Author: github.com/lzl124631x
35+
// Time: O(N^2)
36+
// Space: O(N)
37+
class Solution {
38+
public:
39+
int numTrees(int n) {
40+
vector<int> dp(n + 1);
41+
dp[0] = 1;
42+
for (int i = 1; i <= n; ++i) {
43+
for (int j = 1; j <= i; ++j) dp[i] += dp[j - 1] * dp[i - j];
44+
}
45+
return dp[n];
46+
}
47+
};
48+
```
49+
50+
## Solution 2. Catalan Number
51+
52+
```cpp
53+
// OJ: https://leetcode.com/problems/unique-binary-search-trees
54+
// Author: github.com/lzl124631x
55+
// Time: O(N)
56+
// Space: O(1)
57+
// Ref: https://discuss.leetcode.com/topic/13321/a-very-simple-and-straight-ans-based-on-math-catalan-number-o-n-times-o-1-space
58+
class Solution {
59+
public:
60+
int numTrees(int n) {
61+
long long ans = 1, i;
62+
for (i = 1; i <= n; ++i) ans = ans * (i + n) / i;
63+
return ans / i;
64+
}
65+
};
66+
```

leetcode/96. Unique Binary Search Trees/s1.cpp

-14
This file was deleted.

leetcode/96. Unique Binary Search Trees/s2.cpp

-13
This file was deleted.

0 commit comments

Comments
 (0)