7 lines in Python, 44 ms


  • 10
    M

    n - how many parenthesis can still be opened
    open - how many parenthesis are opened

    class Solution:
        def generateParenthesis(self, n, open=0):
            if n == 0: return [')'*open]
            if open == 0:
                return ['('+x for x in self.generateParenthesis(n-1, 1)]
            else:
                return [')'+x for x in self.generateParenthesis(n, open-1)] + ['('+x for x in self.generateParenthesis(n-1, open+1)]

  • 0
    I

    Wow, this is very clever. Any idea about asymptotic analysis?


  • 0
    J

    Very cool solution!


Log in to reply
 

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