22 Generate Parentheses
使用helper 函数帮助进行迭代,类似于二叉树遍历中后序遍历,先处理左右子树,最后处理根节点。helper 函数的三个参数,剩余的open, 剩余的close,以及当前的字串。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
##
def helper(left, right, current):
if left == 0 and right == 0:
return current
if left > right:
return current
if current == []:
return helper(left-1, right, ["("])
ans = []
for i in current:
if left > 0:
ans.extend(helper(left-1, right, [ i+"(" ]))
if right > 0 and left < right:
ans.extend(helper(left, right-1, [ i+")" ]))
return ans
return helper(n,n,[])