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
一开始是想用递归解决,但看了标签是dp问题,就想了一下, 数目为k的bst,其每个 0 ~ k - 1都可以分成两个区间, 然后又可以生成bst, 所以k的bst种类数等于取k左侧与右侧可划分成bst的乘机的总和,额,有点绕口额,代码清晰一点, 看代码:
class Solution {
public:
int numTrees(int n) {
vector<int> ret;
if(n == ) return ;
ret.reserve(n + );
ret[] = ;
for(int i = ; i <= n; ++i){
if(i < ){
ret[i] = i;
continue;
}
for(int j = ; j < i; ++j){
ret[i] += ret[j] * ret[i - j - ];
}
}
return ret[n];
}
};