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

Base case: n==0, n==1时,f(n)==1

递推关系:f(n)=∑f(i)*f(n-i-1)。即以第i个为根节点,左右子树数目相乘。

解法一:递归

class Solution {
public:
int numTrees(int n) {
if(n == )
return ;
else if(n == )
return ;
else
{
int count = ;
for(int i = ; i <= (n-)/; i ++)
{
if(i < n--i)
count += *numTrees(i)*numTrees(n--i);
else
count += numTrees(i)*numTrees(n--i);
}
return count;
}
}
};

【LeetCode】96. Unique Binary Search Trees (2 solutions)-LMLPHP

解法二:动态规划

class Solution {
public:
int numTrees(int n) {
if(n== || n == )
return ; vector<int> v(n+, );
v[] = ;//n==0
v[] = ;//n==1
for(int i = ; i <= n; i ++)
{//n == i
for(int j = ; j < i; j ++)
{
v[i] += v[j]*v[i--j];
}
}
return v[n];
}
};

【LeetCode】96. Unique Binary Search Trees (2 solutions)-LMLPHP

05-08 15:19