8 lines recursive solution

  • -1

    Idea is very simple:

    for each string in the list returned by generateParenthesis(n-1), put '(' in each possible position, and then put ')' in each possible position after the new '('.

    This general idea is pretty crude. There are numerous places you can improve for speed. But this simple basic one is enough to pass OJ.

    class Solution:
        def generateParenthesis(self, n):
            if n==1:
                return ['()']
            for s in self.generateParenthesis((n-1)):
                results=results | set([s[:i]+'('+s[i:j]+')'+s[j:len(s)] for i in xrange(len(s)+1) for j in xrange(i,len(s)+1)])           
            return list(results)

Log in to reply

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