-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumTrees.cpp
More file actions
32 lines (31 loc) · 744 Bytes
/
numTrees.cpp
File metadata and controls
32 lines (31 loc) · 744 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
31
32
/*
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
*/
//my Solution
class Solution {
public:
int numTrees(int n) {
if(n==1||n==0)
return 1;
int* a=new int[n+1];
a[0]=a[1]=1;
int tmp;
for(int i=2;i<=n;i++)
{
tmp=0;
for(int j=i-1;j>=0;j--)
{
tmp+=a[j]*a[i-1-j];
}
a[i]=tmp;
}
return a[n];
}
};