Java easy solution with hashmap


  • 0
    V
    public class Solution {
        HashMap<Integer, Integer> dp = new HashMap<>();
        public int numTrees(int n) {
            if(n == 0 || n == 1) return 1;
            if(dp.containsKey(n)) return dp.get(n);
            int answer = 0;
            for(int i = 0; i < n; i++){
                answer += (dp.containsKey(i) ? dp.get(i) : numTrees(i)) * (dp.containsKey(n-i-1) ? dp.get(n-i-1) : numTrees(n-i-1));
            }
            dp.put(n, answer);
            return answer;
        }
    }

  • 0
    X
    This post is deleted!

Log in to reply
 

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