Python recursive solution

  • 2
    class Solution:
        # @param an integer
        # @return a list of string
        def generateParenthesis(self, n):
            result = []
            def generate(result, prev, remained_front, allowed_back):
                if remained_front == 0:
                    for i in range(allowed_back):
                        prev += ")"
                if remained_front > 0:
                    generate(result, prev+"(", remained_front-1, allowed_back+1)
                if allowed_back > 0:
                    generate(result, prev+")", remained_front, allowed_back-1)
            generate(result,"(", n-1, 1)
            return result

Log in to reply

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