- #1
member 428835
Hi PF!
Here is a code that generates ##n## amount of valid combinations of parenthesis e.g. n = 2 implies (()), ()(). But this wouldn't work )()( or this ))((.
My issue on understanding it is the function generate. Specifically, when I pass the first ##n=0## case the if statement in line 7 is activated (better word for this?) since _open < n. The variable s is now ( and we are told to plug this back into the generate function. So we do this and again line 7 is activated, so now s is ((. We again plug this back into the generate function only this time line 10 is enabled, changing s to ((), where we go back into the generate function. Lastly, we have (()), again from line 10. This takes care of (()) but what about the ()() solution? How is it being generated? What am I missing?
Here is a code that generates ##n## amount of valid combinations of parenthesis e.g. n = 2 implies (()), ()(). But this wouldn't work )()( or this ))((.
Python:
def generate(result, s, _open, close, n):
# Base condition
if close == n:
result.append(s)
return
# If the number of _open parentheses is less than the given n
if _open < n:
generate(result, s + "(", _open + 1, close, n)
# If we need more close parentheses to balance
if close < _open:
generate(result, s + ")", _open, close + 1, n)
def generateParenthesis(n):
# Resultant list
result = []
# Recursively generate parentheses
generate(result, "", 0, 0, n)
return result
if __name__ == "__main__":
n = 2;
print(generateParenthesis(n))
My issue on understanding it is the function generate. Specifically, when I pass the first ##n=0## case the if statement in line 7 is activated (better word for this?) since _open < n. The variable s is now ( and we are told to plug this back into the generate function. So we do this and again line 7 is activated, so now s is ((. We again plug this back into the generate function only this time line 10 is enabled, changing s to ((), where we go back into the generate function. Lastly, we have (()), again from line 10. This takes care of (()) but what about the ()() solution? How is it being generated? What am I missing?
Last edited by a moderator: