Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
该题目要求输入一个正整数N,打印出所有符合要求的括号组合。
深度优先搜索(DFS): 先定义左括号和右括号的数量, 然后进行DFS, 由于需要产生合法的括号, 那么左括号肯定先用完, 剩余的右括号>= 剩余的左括号. 边界情况(edge case)是是当剩余的右括号<左括号时, 直接返回. 如果不加edge case,有可能会出现类似"(()))("的非法括号. 递归终止条件是当左右括号都用完时, 将path加到结果中.
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
left,right = n,n
if n == 0:
return res
self.dfs(n,n,'',res)
return res
def dfs(self,left,right,path,res):
# edge case: right must >= left
if right<left:
return
if not left and not right:
res.append(path)
if left:
self.dfs(left-1,right,path+'(',res)
if right:
self.dfs(left,right-1,path+')',res)