用 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
輸出
["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP