Skip to content

Commit 29b12dd

Browse files
committed
22. Generate Parentheses
1 parent cf0e236 commit 29b12dd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Given n pairs of parentheses, write a function to generate all combinations of
2+
# well-formed parentheses.
3+
4+
5+
# Example 1:
6+
# Input: n = 3
7+
# Output: ["((()))","(()())","(())()","()(())","()()()"]
8+
9+
# Example 2:
10+
# Input: n = 1
11+
# Output: ["()"]
12+
13+
# Constraints:
14+
# 1 <= n <= 8
15+
16+
17+
class Solution:
18+
def generateParenthesis(self, n: int) -> list[str]:
19+
res = []
20+
def recurs(l, r, s:list[str]):
21+
if l == 0 and r == 0:
22+
res.append(''.join(s))
23+
if l > 0:
24+
s.append('(')
25+
recurs(l-1, r, s)
26+
s.pop()
27+
if l < r:
28+
s.append(')')
29+
recurs(l, r-1, s)
30+
s.pop()
31+
recurs(n, n, [])
32+
return res

0 commit comments

Comments
 (0)