Skip to content

Commit 2f21f3d

Browse files
authored
Create 22-Generate-Parentheses.py
1 parent ff74d3e commit 2f21f3d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

22-Generate-Parentheses.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def generateParenthesis(self, n: int) -> List[str]:
3+
stack = []
4+
res = []
5+
6+
def backtrack(openN, closedN):
7+
if openN == closedN == n:
8+
res.append("".join(stack))
9+
return
10+
11+
if openN < n:
12+
stack.append("(")
13+
backtrack(openN + 1, closedN)
14+
stack.pop()
15+
if closedN < openN:
16+
stack.append(")")
17+
backtrack(openN, closedN + 1)
18+
stack.pop()
19+
20+
backtrack(0, 0)
21+
return res

0 commit comments

Comments
 (0)