Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解题思路
从左到右生成相应的符号序列,首先添加‘(’,左右括号成对出现且个数一致,右边括号计数大于左边括号时需要添加‘)’,直到计数都为0时表示当前生成一个有效的序列,依次递归操作
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def gernerate_str(sstr,lnum,rnum,result=[]): if lnum==0 and rnum==0: result.append(sstr) return if lnum>0: gernerate_str(sstr+'(',lnum-1,rnum,result) if rnum>lnum: gernerate_str(sstr+')',lnum,rnum-1,result) result=[] gernerate_str('',n,n,result) return result