Generate Parentheses
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Solution
@使用DFS,观察上方例子,某一时刻左侧括号必须多于右边,所以先对左侧括号搜索到底部
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n<0:
return []
res = []
self.generate(n,n,'',res)
return res
def generate(self, l, r, str, res):
if l==0 and r==0:
res.append(str)
return
if l>0:
self.generate(l-1, r, str+'(', res)
if r>0 and l<r:
self.generate(l, r-1, str+')', res)