题目描述:
输出n对“()”可能组成的所有合理组合
输入 | n=1 | n=2 | n=3 |
输出 | ['()'] | ['()()','(())'] | ['((()))', '(()())', '(())()', '()(())', '()()()'] |
思路:
由空集合递归生成最后的合乎规定的括号组合问题;
递归调用,最后生成的组合添加到列表中,递归结束;
“(”与“)”成对出现,所以“)”出现的次数<="("出现的次数;
代码
n=3
result=[]
def fun(count,n,string):
l,r=count
if r==n:
result.append(string)
return True
else:
if l>r:
if l<n:
fun([l+1,r],n,string+'(')
fun([l, r + 1], n, string + ')')
elif l==r:
fun([l + 1, r], n, string + '(')
fun([0,0],n,'')
print(result)