-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_parenthesis.py
More file actions
38 lines (26 loc) · 891 Bytes
/
generate_parenthesis.py
File metadata and controls
38 lines (26 loc) · 891 Bytes
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
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
self.result = []
if not n:
return self.result
self.backtrack_parenthesis([],n,n,self.result)
return self.result
def backtrack_parenthesis(self,s,opening,closing,result):
if opening==closing==0:
result.append(''.join(s))
if closing>0 and opening<closing:
s.append(')')
self.backtrack_parenthesis(s,opening,closing-1,result)
s.pop()
if opening>0:
s.append('(')
self.backtrack_parenthesis(s,opening-1,closing,result)
s.pop()
# return result
if __name__ == '__main__':
outpt = ["((()))", "(()())", "(())()", "()(())", "()()()"]
n = 3
sol = Solution()
res = sol.generateParenthesis(n)
print(res)