An iterative method in 4 lines of Python

  • 0
        def generateParenthesis(self, n):
            :type n: int
            :rtype: List[str]
            gp = [['']] + [[] for _ in range(0, n)]
            for i in range(1, n + 1):
                gp[i] += set(['({})'.format(s) for s in gp[i-1]] + ['{}{}'.format(s1, s2) for j in range(1,i) for s1 in gp[j] for s2 in gp[i - j]])
            return gp[n]

Log in to reply

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