用 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