class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
stack = [] # help pairing, only store unpairing '('
s = "("
stack.append('(')
l_count = n-1 # number of left braket usable
r_count = n # number of right braket usable
self.helper(s, stack, result, l_count, r_count)
return result
def helper(self, s, stack, result, l_count, r_count):
# stop condition
if r_count == 0:
if len(stack) == 0: # valid string
result.append(s)
return
# regular case
if len(stack) != 0:
if l_count > 0:
# append '(', then add it to stack
stack.append('(')
temp = stack[:] # 非常关键的一步,一定要深度复制,不然stack随时在改变,影响下一步的stack.pop()
self.helper(s+'(', temp, result, l_count-1, r_count)
stack.pop()
# append ')', then eliminate one '(' from stack
stack.pop()
self.helper(s+')', stack, result, l_count, r_count-1)
else:
stack.pop()
self.helper(s+')', stack, result, l_count, r_count-1)
else:
if l_count > 0:
stack.append('(')
self.helper(s+'(', stack, result, l_count-1, r_count)