在Python中产生括号
假设我们有一个值n。我们必须生成所有可能的格式正确的括号,其中存在n个打开和关闭括号。因此,如果n=3的值,则括号设置为[“()()()”,“()(())”,“(())()”,“(()())“,”(((()))“]
为了解决这个问题,我们将遵循以下步骤-
定义名为的方法genParenthesisRec()。这需要左,右,临时字符串和结果数组。初始结果数组为空
函数genParenthesisRec,将如下工作
如果left=0和right:=0,则将temp插入到结果中,然后返回
如果左>0
getParenthesisRec(左–1,右,温度+“(”,结果)
如果右>左
getParenthesisRec(左,右–1,temp+“)”,结果)
示例(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
输出结果
["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]