-
Notifications
You must be signed in to change notification settings - Fork 4
/
Unique Binary Search Tree.txt
56 lines (46 loc) · 1.8 KB
/
Unique Binary Search Tree.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
problem:
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
-----------------------------------------------------------------------------------
solution:
定义Count[i] 为以[0,i]能产生的Unique Binary Tree的数目,
如果数组为空,毫无疑问,只有一种BST,即空树,
Count[0] =1
如果数组仅有一个元素{1},只有一种BST,单个节点
Count[1] = 1
如果数组有两个元素{1,2}, 那么有如下两种可能
1 2
\ /
2 1
Count[2] = Count[0] * Count[1] (1为根的情况)
+ Count[1] * Count[0] (2为根的情况。
再看一遍三个元素的数组,可以发现BST的取值方式如下:
Count[3] = Count[0]*Count[2] (1为根的情况)
+ Count[1]*Count[1] (2为根的情况)
+ Count[2]*Count[0] (3为根的情况)
所以,由此观察,可以得出Count的递推公式为
Count[i] = ∑ Count[0...k] * [ k+1....i] 0<=k<i-1
问题至此划归为一维动态规划。
//numTrees(i+1)=append the last node to the rightmost leaf of bst(i)[numTrees(i)] +
//append the last node as the root of bst(i)[numTrees(i)] +
//insert the last node as non-leaf node sum(k=1...i)(bst(k-1)*bst(i-k)
//卡特兰数(括号化、出栈次数、凸多边形三角划分、给定结点组成二叉树)
int numTrees(int n)
{
vector<int> bst(n + 1, 0);
bst[0] = 1;
bst[1] = 1;
bst[2] = 2;
for (int i=3; i<=n; i++) {
for (int j=0; j<=i-1; j++) {
bst[i] += bst[j]*bst[i-1-j];
}
}
return bst[n];
}