Skip to content

Commit

Permalink
[LeetCode] generate-parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
ehdgua01 committed Nov 1, 2024
1 parent 554b253 commit d1d2ef7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Empty file.
49 changes: 49 additions & 0 deletions coding_test/leetcode/generate-parentheses/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import List


class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
stack = []

def backtrack(opened: int, closed: int):
if opened == closed == n:
res.append("".join(stack))
return

if opened < n:
stack.append("(")
backtrack(opened + 1, closed)
stack.pop()

if closed < opened:
stack.append(")")
backtrack(opened, closed + 1)
stack.pop()

backtrack(0, 0)
return res


def test():
sol = Solution()
assert sorted(sol.generateParenthesis(1)) == sorted(
[
"()",
]
)
assert sorted(sol.generateParenthesis(2)) == sorted(
[
"(())",
"()()",
]
)
assert sorted(sol.generateParenthesis(3)) == sorted(
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()",
]
)

0 comments on commit d1d2ef7

Please sign in to comment.