Description
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Submissions
我的解题思路是首先题目输入n,就相当于输入有n个左括号和n个右括号,利用递归调用定义的gen函数,首先判断是否是有效括号,左括号数必须小于等于右括号数,同时必须都大于零。添加一个左括号l就减一,同理添加一个右括号r就减一。当左括号数等于右括号数等于零时,将当前的括号组合添加到res列表中。最后返回res列表。
这里参考https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/
从图中可以分析出深度优先遍历的函数包含的步骤为:
(1)当前左右括号都有大于 0 个可以使用的时候,才产生分支;
(2)产生左分支的时候,只看当前是否还有左括号可以使用;
(3)产生右分支的时候,还受到左分支的限制,右边剩余可以使用的括号数量一定得在严格大于左边剩余的数量的时候,才可以产生分支;
(4)在左边和右边剩余的括号数都等于 0 的时候结算。
实现代码如下:
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def gen(l, r, s, res):
if l<0 or r<0 or l>r:
return None
if l==0 and r==0:
res.append(s)
if l>0:
gen(l-1, r, s+'(', res)
if r>0:
gen(l, r-1, s+')', res)
res = []
gen(n, n, '', res)
return res