力扣 22. 括号生成

回溯思想 + 深度优先遍历(dfs)实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def generateParenthesis(n):
res, cur = [], ""
def dfs(cur, left, right):
if left == 0 and right == 0:
res.append(cur)
elif right < left:
return
else:
if left > 0:
dfs(cur + "(", left - 1, right)
if right > 0:
dfs(cur + ")", left, right - 1)
dfs(cur, n, n)
return res
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信