-
Notifications
You must be signed in to change notification settings - Fork 20
/
GenerateParentheses.py
45 lines (40 loc) · 1.04 KB
/
GenerateParentheses.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
# -*- coding: UTF-8 -*-
#
# Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
#
# For example, given n = 3, a solution set is:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
# Python, Python 3 all accepted.
class GenerateParentheses:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
m_set = set()
if n <= 0:
return list(m_set)
if n == 1:
m_set.add("()")
return list(m_set)
for s in self.generateParenthesis(n - 1):
string = ""
chars = list(s)
for j in range(len(chars)):
string += chars[j]
if chars[j] == '(':
builder = "" + string
builder += "()"
for k in range(j + 1, len(chars)):
builder += chars[k]
m_set.add(builder)
m_set.add(s + "()")
return list(m_set)