Created
June 20, 2017 05:36
-
-
Save farkwun/f9f9e1d167aca998427ecec378585931 to your computer and use it in GitHub Desktop.
22. Generate Parentheses - Leetcode
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found that solution very popular and helpful:
https://www.youtube.com/watch?v=N3O1snRqacI&ab_channel=EricProgramming