class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
track = "("
def back_track(track, n):
left_num , right_num = track.count('('), track.count(')')
if left_num == n and right_num == n:
res.append(track)
return
for choice in ['(', ')']:
if choice == '(':
if left_num >= n:
continue
if choice == ')':
if left_num <= right_num :
continue
track += choice
back_track(track, n)
track = track[:-1]
back_track(track, n)
return res
括号生成的剪枝条件是当选择为左括号时,左括号的数量大于等于n
或者选择为右括号时,右括号数量大于等于左括号。