Skip to content

Commit

Permalink
Update generate-parentheses.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 21, 2020
1 parent 7132f3c commit d771c5d
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions Python/generate-parentheses.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,26 @@ def generateParenthesis(self, n):
:type n: int
:rtype: List[str]
"""
result = []
stk = [("", n, n)]
result, curr = [], []
stk = [(1, (n, n))]
while stk:
curr, left, right = stk.pop()
if left == 0 and right == 0:
result.append(curr)
if left < right:
stk.append((curr+")", left, right-1))
if left > 0:
stk.append((curr+"(", left-1, right))
step, args = stk.pop()
if step == 1:
left, right = args
if left == 0 and right == 0:
result.append("".join(curr))
if left < right:
stk.append((3, tuple()))
stk.append((1, (left, right-1)))
stk.append((2, (')')))
if left > 0:
stk.append((3, tuple()))
stk.append((1, (left-1, right)))
stk.append((2, ('(')))
elif step == 2:
curr.append(args[0])
elif step == 3:
curr.pop()
return result


Expand All @@ -30,14 +40,18 @@ def generateParenthesis(self, n):
:type n: int
:rtype: List[str]
"""
def generateParenthesisRecu(result, current, left, right):
def generateParenthesisRecu(left, right, curr, result):
if left == 0 and right == 0:
result.append(current)
result.append("".join(curr))
if left > 0:
generateParenthesisRecu(result, current + "(", left-1, right)
curr.append('(')
generateParenthesisRecu(left-1, right, curr, result)
curr.pop()
if left < right:
generateParenthesisRecu(result, current + ")", left, right-1)
curr.append(')')
generateParenthesisRecu(left, right-1, curr, result)
curr.pop()

result = []
generateParenthesisRecu(result, "", n, n)
generateParenthesisRecu(n, n, [], result)
return result

0 comments on commit d771c5d

Please sign in to comment.