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
// Source : https://oj.leetcode.com/problems/unique-binary-search-trees/
// Author : Chao Zeng
// Date : 2014-12-18
class Solution {
public:
int numTrees(int n) {
return combination(2*n,n)/(n + 1);
}
int64_t combination(int num1, int num2){
int64_t ans1 = 1, ans2 = 1;
int i;
for (i = num1; i > num2; i--)
ans1*=i;
for (i = num2; i > 0; i--)
ans2*=i;
return ans1 / ans2;
}
};