#22
Generate Parentheses
medium· Stackruns: 0Given an integer n, return all combinations of n pairs of well-formed parentheses.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 647
class Solution:
def generateParenthesis(self, n: int) -> list[str]:
result = []
stack = []
def backtrack(open_count: int, close_count: int) -> None:
if open_count == close_count == n:
result.append("".join(stack))
return
if open_count < n:
stack.append("(")
backtrack(open_count + 1, close_count)
stack.pop()
if close_count < open_count:
stack.append(")")
backtrack(open_count, close_count + 1)
stack.pop()
backtrack(0, 0)
return result
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.