-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22_generate_parentheses.py
More file actions
36 lines (33 loc) · 1.43 KB
/
Copy path22_generate_parentheses.py
File metadata and controls
36 lines (33 loc) · 1.43 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
class Solution(object):
# lookup table for n in [0, 3]
lookup = { 0: ['()'], 1: ['()()', '(())'], 2: ['()(())', '((()))', '(())()', '(()())', '()()()'], 3: ['()(()())', '(()())()', '((()()))', '(()()())', '((())())', '(()(()))', '()()()()', '(())()()', '()(())()', '()()(())', '((()))()', '(())(())', '()((()))', '(((())))'] }
def generate(self, _list):
h = {}
for e in _list:
for key in { '()' + e, e + '()', '(' + e + ')' }:
if key not in h:
h[key] = ''
index = 0
while index < len(e):
if e[index:index + 2] == '()':
for key in [ e[0:index] + '()()' + e[index + 2:], e[0:index] + '(())' + e[index + 2:] ]:
if key not in h:
h[key] = ''
index += 1
index += 1
return list(h.keys())
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
index = min(len(Solution.lookup), n) - 1
permutations = Solution.lookup[index]
for i in range(n - index - 1):
permutations = self.generate(permutations)
if index + i + 1 < 8 and (index + i + 1 not in Solution.lookup):
Solution.lookup[index + i + 1] = permutations
return permutations
n = 8
Solution().generateParenthesis((n))
print(Solution().generateParenthesis((n)))