96. Unique Binary Search Trees!

class Solution {
    public int numTrees(int n) {
        // dp problem
        // binary search tree: right>node>left
        // dp[i] = dp[i-1]*dp[0] +dp[i-2]*dp[i]+...dp[0]*dp[i-1];
        int[] memo = new int[n+1];
        memo[0]=1;
        memo[1]=1;
        for (int i=2; i<=n; i++){
            for(int j=0; j<i; j++){
                memo[i]+=memo[i-1-j]*memo[j];
            }
        }
        return memo[n];
    }
}

Last updated