22_Generate Parentheses
Last updated
Last updated
def generateParenthesis(n):
"""
:type n: int
:rtype: List[str]
"""
def helper(left, right, prefix):
# left is the number of "(" remains to be added
# right is the number of ")" remains to be added
# prefix is the parentheses already added
if right == 0:
output.append(prefix)
return
# case when we are able to insert "("
if left > 0:
helper(left-1, right, prefix + "(")
# case when we are able to insert ")"
if right > left:
helper(left, right - 1, prefix + ")")
output = []
helper(n, n, "")
return output