22-Generate Parenthesis

题目:输入括号对数n,返回合法的括号形式

def generateParenthesis(n):
    res = []
    gen(0,0,n,res,'')
    return res

def gen(left,right,n,res,path):
    if left == n and right == n:
        res.append(path)
        return
    if left < n:
        gen(left+1,right,n,res,path+'(')
    if left>right and right<n:
        gen(left,right+1,n,res,path+')')

注:

使用递归来做,用left,right分别表示左右括号的使用数量。当两者使用数量为n时,表示已经找出一种情况。如果left小于n,则可以继续加入'(';右括号的情况不仅要小于n,还需要保证right<left,才能保证最终括号的合法性。

原文地址:https://www.cnblogs.com/kingshine007/p/11379683.html