Skip to content

Commit

Permalink
Create 22-Generate-Parentheses.py
Browse files Browse the repository at this point in the history
  • Loading branch information
neetcode-gh authored Dec 25, 2021
1 parent ff74d3e commit 2f21f3d
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 22-Generate-Parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
stack = []
res = []

def backtrack(openN, closedN):
if openN == closedN == n:
res.append("".join(stack))
return

if openN < n:
stack.append("(")
backtrack(openN + 1, closedN)
stack.pop()
if closedN < openN:
stack.append(")")
backtrack(openN, closedN + 1)
stack.pop()

backtrack(0, 0)
return res

0 comments on commit 2f21f3d

Please sign in to comment.