22. Generate Parentheses
- Generate Parentheses python solution
题目描述
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:

解析
还是要采用递归的思想解题。但一定要保证任何时刻"(“的个数要多于”)“的个数。
若出现”)("就绝不可能形成有效的括号
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if not n:
return []
left, right, ans=n,n,[]
self.dfs(left,right,ans,"")
return ans
def dfs(self,left,right,ans, string):
if left>right:
return
if not left and not right:
ans.append(string)
if left:
self.dfs(left-1,right,ans,string+"(")
if right:
self.dfs(left,right-1,ans,string+")")
代码的可视化如下
For Visualization:
dfs(2, 2, [], "")
dfs(1, 2, [], "(")
dfs(0, 2, [], "((")
dfs(0, 1, [], "(()")
dfs(0, 0, [], "(())") # We got "(())" and we append it to ans
dfs(1, 1, ["(())"], "()")
dfs(0, 1, ["(())"], "()(")
dfs(0, 0, ["(())"], "()()") # We got "(())" and we append it to ans
dfs(1, 0, ["(())", "()()"], "())") # will just return as right < left
dfs(2, 1, ["(())", "()()"], ")") # will just return as right < left
Reference
https://leetcode.com/problems/generate-parentheses/discuss/10110/Simple-Python-DFS-solution-with-explanation
本文深入探讨了如何使用递归算法解决括号生成问题,详细解释了确保括号配对正确的核心思想,并提供了Python实现代码及可视化过程。
416

被折叠的 条评论
为什么被折叠?



