Java clear DP solution using a memo array to store the past results


  • 0
    W
    public class Solution {
        public int numTrees(int n) {
            return helper(n, new int[n+1]);
        }
        
        int helper(int n, int[] cache) {
            if(n == 0 || n == 1)    return 1;
            if(cache[n] == 0) {
                for(int i = 1; i<= n; i++) {
                    cache[n] += helper(i-1, cache) * helper(n-i, cache);
                }
            }
            return cache[n];
        }
    }
    

Log in to reply
 

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