Skip to content

Instantly share code, notes, and snippets.

@farkwun
Created June 20, 2017 05:36
Show Gist options
  • Save farkwun/f9f9e1d167aca998427ecec378585931 to your computer and use it in GitHub Desktop.
Save farkwun/f9f9e1d167aca998427ecec378585931 to your computer and use it in GitHub Desktop.
22. Generate Parentheses - Leetcode
# https://leetcode.com/problems/generate-parentheses/#/description
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
return(self.createParentheses("", n, n))
def createParentheses(self, string, num_open, num_closed):
if num_open == num_closed == 0:
return [string]
answer_strings = []
if num_open == num_closed:
for s in self.createParentheses(string + "(", num_open - 1, num_closed):
answer_strings.append(s)
elif num_open > 0 and num_open < num_closed:
for s in self.createParentheses(string + "(", num_open - 1, num_closed):
answer_strings.append(s)
for s in self.createParentheses(string + ")", num_open, num_closed - 1):
answer_strings.append(s)
elif num_open == 0:
for s in self.createParentheses(string + ")", num_open, num_closed - 1):
answer_strings.append(s)
return answer_strings
@QureshiAbraham
Copy link

I found that solution very popular and helpful:
https://www.youtube.com/watch?v=N3O1snRqacI&ab_channel=EricProgramming

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment