Store values in Class variable. Faster than 99%. Python.


  • 0
    M

    Keeping previously calculated values in storeArr so that we don't have to recalculate them again.

    class Solution(object):
    
    storeArr = [[],["()"]]
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        if n < len(Solution.storeArr):
            return Solution.storeArr[n]
        for i in range(len(Solution.storeArr),n+1):
            temp = []
            lastArr = Solution.storeArr[-1]
            for item in lastArr:
                xArr = list(item)
                for i in range(1,len(xArr)):
                    temp.append("".join(xArr[:i]+["()"]+xArr[i:]))
                temp.append("".join(["()"]+xArr))
                temp.append("".join(xArr+["()"]))
            Solution.storeArr.append(list(set(temp)))
        return Solution.storeArr[n]

Log in to reply
 

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