Python recursion and global cache


  • 0
    Z
    cache = {}
    class Solution(object):
        def numTrees(self, n):
            def helper(n):
                if n in cache: return cache[n]
                res = sum([(helper(i) or 1) * (helper(n - i - 1) or 1) for i in xrange(n)])
                cache[n] = res
                return res
            return helper(n)
    

Log in to reply
 

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