[Leetcode 75] 96 Unique Binary Search Trees
Problem:
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
Analysis:
Simple enumeration is not possible. But the problem can be solved by making use of the recursive property of tree and dynamic programming method.
For n = 3, we can choose 1, 2 or 3 as the root of the tree.
For root is 1, then the tree contains one 2 nodes subtree and a two node tree's unique structure number is 2.
For root is 2, then the tree contains two 1 node subtree and the number of unique structure for each tree is 1, so the final number is 1 * 1 = 1.
For root is 3, the situation is similar as root 1 except the subtree changing from right subtree to left subtree. the number is 2.
So the total number of n =3 is 5.
Other n values can also be computed the same way as mentioned above. Several things to remember:
1. for two subtree with node n1 and n2, the unique of the whole tree is num[n1] * num[n2]
2. due to the symmetric property, we can only go through n/2 values to get the value
3. pay attention to odd n values. there's an extra item num[n/2] * num[n/2] to be computed.
This DP method only need to go through n/2 values and thus the time complecity is O(n). Since we keep record of all the values that is less than n, the space requirement is O(n).
Code:
1 class Solution { 2 public: 3 int numTrees(int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (n == 0 || n == 1) 7 return n; 8 9 int tab[n+1]; 10 tab[0] = 0; tab[1] = 1; 11 for (int i=2; i<=n; i++) { 12 tab[i] = compute(i, tab); 13 } 14 15 return tab[n]; 16 } 17 18 int compute(int n, int *a) { 19 int r = 2 * a[n-1]; 20 21 for (int i=1; i<n/2; i++) { 22 r += 2 * (a[i] * a[n-1-i]); 23 } 24 25 if (n%2) { 26 r += (a[n/2] * a[n/2]); 27 } 28 29 return r; 30 } 31 };