LeetCode 22. Generate Parentheses 回溯 backtrack

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

------------------------------

Simple codes:

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        def backtrack(p, left, right):
            nonlocal res
            if (left > 0):
                backtrack(p + "(", left-1, right)
            if (left < right):
                backtrack(p + ")", left, right-1)
            if (right == 0):
                res.append(p)
        backtrack("", n, n)
        return res

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章