Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created August 27, 2015 06:16
Show Gist options
  • Save junjiah/0925ef3e14fdb52c3be7 to your computer and use it in GitHub Desktop.
Save junjiah/0925ef3e14fdb52c3be7 to your computer and use it in GitHub Desktop.
solved 'Generate Parentheses' on LeetCode https://leetcode.com/problems/generate-parentheses/
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.valid_parens = []
self.n = n
# 0 open, 0 closed, recursively build valid strings.
self.buildParenString(0, 0, '')
return self.valid_parens
def buildParenString(self, opened, closed, curr_str):
if closed == self.n:
self.valid_parens.append(curr_str)
else:
# Open another parenthesis if possible.
if opened < self.n:
self.buildParenString(opened + 1, closed, curr_str + '(')
# Can only close them if there is more opened brackets.
if opened > closed:
self.buildParenString(opened, closed + 1, curr_str + ')')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment