-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unique_Binary_Search_Trees.txt
38 lines (30 loc) · 1.02 KB
/
Unique_Binary_Search_Trees.txt
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
31
32
33
34
35
36
37
38
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
class Solution {
public:
int numTrees(int n) {
//vec[n] counts the number of unique BST with n nodes.
vector<int> vec(n+1,0); //(n+1) ints with value 0
vec[0]=1;
vec[1]=1;
for(int i=2; i<=n; ++i){
for (int j=0; j<i; ++j){
vec[i] += vec[j]*vec[i-j-1];
}
}
return vec[n];
}
};
REMARK:
1. IDEA: use DP(dynamic programming) to solve it, that is, for example:
Count[n] counts the number of unique BST with n nodes.
Count[3] = Count[0]*Count[2] (1 is the root)
+ Count[1]*Count[1] (2 is the root)
+ Count[2]*Count[0] (3 is the root)
2. However, the index issue can be annoying.