-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path9.6.matching_paren.py
More file actions
54 lines (45 loc) · 1.53 KB
/
Copy path9.6.matching_paren.py
File metadata and controls
54 lines (45 loc) · 1.53 KB
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
# 12:20
class ParenGenerator:
def __init__(self, n):
self.openCount = self.closeCount = n
self.output = []
def generateParen(self, openCount = 0, closeCount = 0):
if openCount > self.openCount or closeCount > openCount:
return None
if openCount + closeCount == self.openCount + self.closeCount:
print ''.join(self.output)
return None
if openCount < self.openCount:
self.output.append('(')
openCount += 1
self.generateParen(openCount, closeCount)
self.output.pop()
openCount -= 1
if openCount > closeCount and closeCount < self.closeCount:
self.output.append(')')
closeCount += 1
self.generateParen(openCount, closeCount)
self.output.pop()
closeCount -= 1
def generateParenthesis(n, openCount = 0, closeCount = 0, output = []):
if openCount > n or closeCount > openCount:
return None
if openCount + closeCount == 2 * n:
print ''.join(output)
return None
if openCount < n:
output.append('(')
openCount += 1
generateParenthesis(n, openCount, closeCount, output)
output.pop()
openCount -= 1
if openCount > closeCount and closeCount < n:
output.append(')')
closeCount += 1
generateParenthesis(n, openCount, closeCount, output)
output.pop()
closeCount -= 1
if __name__ == '__main__':
# p = ParenGenerator(1)
# p.generateParen()
generateParenthesis(2)