用 Python 生成括號


假設我們有一個值 n。我們必須生成所有可能的括號序列,其中包含 n 個開括號和閉括號。因此,如果 n 的值為 3,則括號序列將為 ["()()()","()(())","(())()","(()())","((()))"]

要解決這個問題,我們將按照以下步驟操作 -

  • 定義一個名為 genParenthesisRec() 的方法。此方法使用左括號、右括號、臨時字串和結果陣列。最初結果陣列是空的
  • genParenthesisRec 函式將如下工作
  • 如果 left = 0 且 right := 0,插入 temp 到 result,返回
  • 如果 left > 0
    • getParenthesisRec(left – 1, right, temp + “(”, result)
  • 如果 right > left
    • getParenthesisRec(left, right – 1, temp + “)”, result)

示例(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

輸出

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

更新於:2020 年 4 月 27 日

2K+ 瀏覽量

開始你的職業生涯

完成相應課程以獲得認證

開始學習
廣告
© . All rights reserved.