Tuesday, March 3, 2015

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
Solution1: Catalan Number
Catalan Number 


所以Cn = 2(2n-1)*Cn-1/(n+1)
Run time complexity is O(n), constant space.
public class Solution {
    public int numTrees(int n) {
        int result = 1;
        for(int i = 2; i <= n; i++) {
            result = 2*(2*i-1)*result/(i+1);
        }
        return result;
    }
}
Solution2 DP

维护量res[i]表示含有i个结点的二叉查找树的数量。根据上述递推式依次求出1到n的的结果即可。
时间上每次求解i个结点的二叉查找树数量的需要一个i步的循环,总体要求n次,所以总时间复杂度是O(1+2+...+n)=O(n^2)。空间上需要一个数组来维护,并且需要前i个的所有信息,所以空间上是O(n)
public class Solution {
    public int numTrees(int n) {
        if(n <= 0)
            return 0;
        
        int[] res = new int[n + 1];
        res[0] = 1;
        res[1] = 1;
        for(int i = 2; i <= n; i++) {
            for(int j = 0; j < i; j++ ) {
                res[i] += res[j] * res[i - j - 1];
            }
        }
        return res[n];
    }
}

No comments:

Post a Comment