My simple java solution with explanation


  • 2
    L

    It's a typical Catalan number. If you'r familiar with it, it can be easily solved by the expression using dynamic programming.Here's the expression and wiki link
    Catalan number
    https://en.wikipedia.org/wiki/Catalan_number

    public class Solution {
        public int numTrees(int n) {
            int[] res = new int[n+1];
            res[0] = 1;
            res[1] = 1;//base case
            for (int i = 2; i <= n; i++) {
                for (int j = 0; j < i; j++) {
                    res[i] += res[j]*res[i-j-1];//result for i nodes is the sum of multiplications of all left subtrees and all right subtrees
                }
            }
            return res[n];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.