Created
August 27, 2015 06:16
-
-
Save junjiah/0925ef3e14fdb52c3be7 to your computer and use it in GitHub Desktop.
solved 'Generate Parentheses' on LeetCode https://leetcode.com/problems/generate-parentheses/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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