-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgen_parens.py
60 lines (50 loc) · 1.47 KB
/
gen_parens.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def generate_parenthesis(n):
"""
Given n pairs of parentheses, write a function to generate all
combinations of well-formed parentheses.
For n=3 the solution is:
"((()))", "(()())", "(())()", "()(())", "()()()"
For each opening bracket we can either start a new opening
bracket or close it and track back.
"""
if n == 0:
return []
def all_combinations(braces, opening=0, closing=0):
if len(braces) >= 2*n:
yield braces
return
if opening < n:
for c in all_combinations(braces + ["("], opening+1, closing):
yield c
if closing < opening:
for c in all_combinations(braces + [")"], opening, closing+1):
yield c
return ["".join(p) for p in all_combinations([])]
def test_generate_parenthesis():
assert generate_parenthesis(0) == []
assert generate_parenthesis(1) == ["()"]
assert generate_parenthesis(2) == ["(())", "()()"]
assert generate_parenthesis(3) == [
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
assert len(generate_parenthesis(4)) == 14
assert generate_parenthesis(4) == [
"(((())))",
"((()()))",
"((())())",
"((()))()",
"(()(()))",
"(()()())",
"(()())()",
"(())(())",
"(())()()",
"()((()))",
"()(()())",
"()(())()",
"()()(())",
"()()()()"
]