-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0022_Generate_Parentheses.py
40 lines (31 loc) · 1.12 KB
/
0022_Generate_Parentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from typing import List
from unittest import TestCase, main
def generateParentheses(n: int) -> List[str]:
combinations = []
def generate(builder: List[str], left: int, right: int):
nonlocal combinations
if not left and not right:
combinations.append("".join(builder))
return
if left > 0:
builder.append("(")
generate(builder, left - 1, right)
builder.pop()
if right > left:
builder.append(")")
generate(builder, left, right - 1)
builder.pop()
generate([], n, n)
return combinations
class Test(TestCase):
def test_zero_pairs(self):
self.assertEqual(generateParentheses(0), [""])
def test_one_pair(self):
self.assertEqual(generateParentheses(1), ["()"])
def test_three_pairs(self):
self.assertEqual(
set(generateParentheses(3)),
set(["((()))", "(()())", "(())()", "()(())", "()()()"])
)
if __name__ == "__main__":
main()