LeetCode 22. Generate Parentheses解题报告(python)

22. Generate Parentheses

  1. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值