96. Unique Binary Search Trees
96. Unique Binary Search Trees
Medium
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: 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
not difficult, it is easy
first you should decide the root num, then the litter num is left of it, the bigger nums are right of it;
we can get that
f(n) = f(n-1) + f(1) * f(n-2) + f(2) * f(n-3) +... + f(n-2) * f(1) + f(n-1)
we can makesure that f(0) = 1
and then
f(n) = ∑f(k) * f(n-1-k)
so we use db solution
class Solution {
public:
vector<int> kinds_num(int n){
vector<int> result;
result.push_back(1);
for (int i=1;i<=n;i++){
int tmp = 0;
for (int j=0;j<=i-1;j++){
tmp += result[j] * result[i-1-j];
}
result.push_back(tmp);
}
return result;
}
int numTrees(int n) {
vector<int> result;
result = kinds_num(n);
return result[n];
}
};