-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path096. Unique Binary Search Trees.cpp
More file actions
30 lines (27 loc) · 995 Bytes
/
096. Unique Binary Search Trees.cpp
File metadata and controls
30 lines (27 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//https://ithelp.ithome.com.tw/articles/10216235
//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Unique Binary Search Trees.
//Memory Usage: 6.1 MB, less than 100.00% of C++ online submissions for Unique Binary Search Trees.
class Solution {
public:
int numTrees(int n) {
vector<int> T(n+1, 0);
T[0] = T[1] = 1;
for(int r = 2; r <= n; r++){
for(int mid = 1; mid <= r; mid++){
/*
if the tree is rooted at mid,
the left and right subtree would be:
[1...mid-1] and [mid+1...r]
since the right subtree's max size is r-1,
so mid starts from 1,
and since the left subtree's max size is r-1,
so mid ends at r
*/
T[r] += T[mid-1] * T[r-mid];
}
// cout << T[r] << " ";
}
// cout << endl;
return T[n];
}
};