Unique Binary Search Trees

Unique Binary Search Trees


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
2
3
4
5
1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

比较像矩阵链乘:取不同的分界点作为根,求两边的子树数量的乘积。

递归形式的AC代码,对迭代递推还是不够熟练:

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
class Solution {
public:

vector<vector<int>> DP;

int solve(int begin, int end)
{

if (begin >= end) return 1;
if (DP[begin][end]) return DP[begin][end];
int f = 0;
for (int i = begin; i <= end; ++i)
{
int r = solve(begin,i-1);
int l = solve(i+1,end);
f += r * l;
}
DP[begin][end] = f;
return f;
}

int numTrees(int n) {
if (1 >= n) return 1;
DP = vector<vector<int>>(n+1,vector<int>(n+1,0));
solve(1,n);
int result = 0;
return DP[1][n];
}
};