Original link: https://leetcode-cn.com/problems/generate-parentheses/
Ideas:
The brute force method is to recursively generate all combinations, and at the same time determine whether they meet the requirements
Backtracking method, there is no need to judge after generating a complete combination, because there are at most two placement methods at each position: when there is still a left parenthesis, place the left parenthesis; the number of left parentheses that have been placed in the current combination When greater than the number of right parentheses, place the right parenthesis
Then take a step back, reverse the operation status value (here the status value is temporary storage space), and see which situation remains next
Code:
classSolution:defgenerateParenthesis(self, n:int)-> List[str]:
result =[]if n<=0:return result
defback(temp, left, right):# 满足组合长度的条件,不需要判断是因为组合生成的方式保证了合理性iflen(temp)==2*n:
result.append(''.join(temp))return# 还有左括号剩余if left<n:
temp.append('(')
back(temp, left+1, right)# 逆操作状态值
temp.pop()# 已使用的左括号的个数大于右括号,说明此时放入右括号一定有左括号与其匹配if left>right:
temp.append(')')
back(temp, left, right+1)
temp.pop()
back([],0,0)return result