96. Unique Binary Search Trees
Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?
For example,
Givenn= 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
Analysis:
DP approach. a[n] = a[0]*a[n-1] + a[1]*a[n-2] + ... + a[n-1]*a[0]
Complexity:
Time: O(n^2) = n-1 + n-2 + .. + 2 = n^2
Space: O(n)
Code:
public class Solution {
int[] arr;
public int numTrees(int n) {
if(n == 0)
{
return 0;
}
arr = new int[n+1];
arr[0] = 1;
arr[1] = 1;
for(int i=2; i<=n; i++)
{
int treeNum = 0;
for(int j=0; j<=i-1; j++)
{
treeNum += arr[j] * arr[i-1-j];
}
arr[i] = treeNum;
}
return arr[n];
}
}