96. Unique Binary Search Trees

Description

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Constraints

Approach

Examples

Input: 3

Output: 5

Explanation: Given n = 3, there are a total of 5 unique BST's,

Solutions

/**
 * Time complexity : The main computation of the algorithm is done at the 
 *    statement with G[i]. So the time complexity is essentially the number 
 *    of iterations for the statement, which is ∑(i=2 to n) i = (2+n)(n−1)/2, 
 *    to be exact, therefore the time complexity is O(N^2).
 * Space complexity : The space complexity of the above algorithm is mainly 
 *    the storage to keep all the intermediate solutions, therefore O(N).
 */

class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        for(int i = 2; i <= n; i++) {
            for(int j = 0; j < i; j++) {
                dp[i] += (dp[j] * dp[i-j-1]);
            }
        }
        return dp[n];
    }
}

Follow up

Last updated

Was this helpful?