-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathA_gen_parenthesis.py
38 lines (30 loc) · 937 Bytes
/
A_gen_parenthesis.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
class Bracket:
def __init__(self):
self.brackets = []
def push(self, bracket):
self.brackets.append(bracket)
def pop(self):
self.brackets.pop()
def peek(self):
return self.brackets[-1]
def is_empty(self):
return self.brackets == []
def gen_parenthesis(n, parenthesis=''):
if n == 0:
brackets = {'(': ')', '[': ']', '{': '}'}
seq = Bracket()
for bracket in parenthesis:
if bracket in brackets.keys():
seq.push(bracket)
elif not seq.is_empty() and bracket == brackets[seq.peek()]:
seq.pop()
else:
seq.push(bracket)
break
if seq.is_empty():
print(parenthesis)
else:
gen_parenthesis(n - 1, parenthesis + '(')
gen_parenthesis(n - 1, parenthesis + ')')
if __name__ == '__main__':
gen_parenthesis(2 * 2)