Concise Recursive Python with Clear Explanations

  • 0
    • (B.C.) : list itemOur base case is when n = 1 we return ["()"].
    • (I.H.) : Assume f(n-1) returns us all combinations of well-formed parentheses.
    • (I.S.): To get f(n), we simply add () to each element inside that combinations.
    class Solution(object):
        def generateParenthesis(self, n):
            if n == 1:
                return ["()"]
            result = set()
            recur = self.generateParenthesis(n - 1)
            for elm in recur:
                for j in range(len(elm)):
                    result.add(elm[:j] + "()" + elm[j:])
            return list(result)

Log in to reply

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