題目描述
給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。
思路
代碼
from typing import List
class Solution():
def generateParenthesis()->List(str):
res = []
cur_str = ''
def dfs(cur_str,left,right):
if left == 0 and right == 0:
res.append(cur_str)
return
if left > right:
return
if left > 0:
dfs(cur_str + '(',left - 1,right)
if right > 0:
dfs(cur_str + ')',left,right - 1)
dfs(cur_str, n, n)
return res