


python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
m = n * 2
ans = []
path = [''] * m
def dfs(i, left):
if i == m:
ans.append(''.join(path))
return
# 选(选的条件)
# 可以选左 left parenthesis can be chosen
if left < n:
path[i] = '('
dfs(i+1, left+1)
# 不选(右)(选择右边的条件)
# 可以选右 right parenthesis can be chosen
right = i - left
if right < left:
path[i] = ')'
dfs(i+1, left)
dfs(0, 0)
return ans
方法一:枚举当前位置填左括号还是右括号(选或不选)
python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
path = [''] * (n * 2) # 所有括号长度都是 2n
# 目前填了 left 个左括号,right 个右括号
def dfs(left: int, right: int) -> None:
if right == n: # 填完 2n 个括号
ans.append(''.join(path))
return
if left < n: # 可以填左括号
path[left + right] = '(' # 直接覆盖
dfs(left + 1, right)
if right < left: # 可以填右括号
path[left + right] = ')' # 直接覆盖
dfs(left, right + 1)
dfs(0, 0) # 一开始没有填括号
return ans
作者:灵茶山艾府
链接:https://leetcode.cn/problems/generate-parentheses/solutions/2071015/hui-su-bu-hui-xie-tao-lu-zai-ci-pythonja-wcdw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:枚举下一个左括号的位置
python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
path = [] # 记录左括号的下标
# 目前填了 i 个括号
# balance = 这 i 个括号中的左括号个数 - 右括号个数
def dfs(i: int, balance: int) -> None:
if len(path) == n:
s = [')'] * (n * 2)
for j in path:
s[j] = '('
ans.append(''.join(s))
return
# 枚举填 right=0,1,2,...,balance 个右括号
for right in range(balance + 1):
# 先填 right 个右括号,然后填 1 个左括号,记录左括号的下标 i+right
path.append(i + right)
dfs(i + right + 1, balance - right + 1)
path.pop() # 恢复现场
dfs(0, 0)
return ans
作者:灵茶山艾府
链接:https://leetcode.cn/problems/generate-parentheses/solutions/2071015/hui-su-bu-hui-xie-tao-lu-zai-ci-pythonja-wcdw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。