22. Generate Parentheses

Generate Parentheses - LeetCode

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ “((()))”, “(()())”, “(())()”, “()(())”, “()()()” ]

  • code
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        def dfs(start, end, path):
            if len(path) == 2 * n:
                res.append("".join(path))
                return
            if start < n:
                dfs(start + 1, end, path + ["("])
            if end < start:
                dfs(start, end + 1, path + [")"])
        dfs(0, 0, [])
        return res