在 Python 中生成括号

pythonserver side programmingprogramming更新于 2025/10/25 14:36:17

假设我们有一个值 n。我们必须生成所有可能的格式正确的括号,其中存在 n 个左括号和右括号。因此,如果 n 的值 = 3,则括号集将为 ["()()()","()(())","(())()","(()())","((()))"]

为了解决这个问题,我们将遵循以下步骤 −

  • 定义名为 genParenthesisRec() 的方法。这需要左、右、临时字符串和结果数组。最初结果数组为空
  • 函数 genParenthesisRec 将按以下方式工作
  • 如果 left = 0 且 right := 0,则将 temp 插入结果并返回
  • 如果 left > 0
    • getParenthesisRec(left – 1, right, temp + “(”, result)
  • 如果 right > left
    • getParenthesisRec(left, right – 1, temp + “)”, result)

Example(Python)

让我们看下面的实现,以便更好地理解 −

class Solution(object):
   def generateParenthesis(self, n):
      """
      :type n: int
      :rtype: List[str]
      """
      result = []
      self.generateParenthesisUtil(n,n,"",result)
      return result
   def generateParenthesisUtil(self, left,right,temp,result):
      if left == 0 and right == 0:
         result.append(temp)
         return
      if left>0:
         self.generateParenthesisUtil(left-1,right,temp+'(',result)
      if right > left:
         self.generateParenthesisUtil(left, right-1, temp + ')', result)
ob = Solution()
print(ob.generateParenthesis(4))

输入

4

输出

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

相关文章


有用资源