题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型
# @return string字符串一维数组
#
class Solution:
def generateParenthesis(self , n: int) -> List[str]:
# write code here
m = n * 2
path = [''] * m
ans = []
def dfs(i: int, open: int) -> None:
if i == m:
ans.append(''.join(path.copy()))
return
if open < n:
path[i] = '('
dfs(i + 1, open + 1)
if i - open < open: # 可以写右括号
path[i] = ')'
dfs(i + 1, open)
dfs(0, 0)
return ans

