https://leetcode.com/problems/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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
想法就是:左括号个数<n时,l+1,dfs左括号
右括号<左括号时,r+1,dfs右括号
l+r==2*n时,添加结果
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res=[]
self.dfs(n,0,0,[],res)
return res
def dfs(self,n,l,r,cur,res):
if l+r==2*n:
res.append("".join(cur))
return
if l<n:
self.dfs(n,l+1,r,cur+["("],res)
if r<l:
self.dfs(n,l,r+1,cur+[")"],res)