题目

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:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def generateParenthesis(self, n):
def backtrace(l, s, open, close, m):
if len(s) == m*2:
l.append(s)
if open < m:
backtrace(l, s+"(", open+1, close, m)
if close < open:
backtrace(l, s+")", open, close+1, m)
r = []
backtrace(r, "", 0, 0, n)
return r