AC O(N) C# code


  • -1
    D
    public class Solution {
        
        Dictionary<int, int> cache = new Dictionary<int,int>();
        public int NumTrees(int n) {
            int outValue = 0;
            if(cache.TryGetValue(n, out outValue)) return outValue;
    
            if(n == 1 || n == 0) {
                return 1;
            }
            
            int num = 0;
            for(int i=1;i<=n; i++){
                num = num + NumTrees(i -1) * NumTrees(n-i);
                
            }
            
            if(!cache.ContainsKey(n)) cache.Add(n, num);
            return num;
        }
    }

Log in to reply
 

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