[leetcode] 22. Generate Parentheses - 括号生成

本文深入探讨了如何通过深度优先搜索算法,生成所有合法的n对括号组合。提供了C++与Python实现代码,详细解释了算法逻辑,包括递归过程与合法性检查,帮助读者理解并实现括号生成问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

分析

题目的意思是:给你n对括号,然后输出其所有的组合方式。

  • 这是一个深度优先搜索的题目,注意left代表剩余的左括号,right表示剩余的右括号;在任意时刻,左括号数目要大于右括号数目。

1)left大于right(left和right分别表示剩余左右括号的个数),即,临时变量中右括号的数大于左括号的数,则说明出现了“)(”,这是非法情况,返回即可;

2)left和right都等于0说明,临时变量中左右括号数相等,所以将临时变量中的值存入res中;

3)其余的情况是,先放左括号,然后放右括号,然后递归。注意参数的更新。

C++代码

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        DFS(n,n,"",result);
        return result;
    }
    void DFS(int left,int right,string res,vector<string> &result){
        if(left>right){
            return;
        }
        if(left==0&&right==0){
            result.push_back(res);
        }else{
            if(left>0){
                DFS(left-1,right,res+"(",result);
            }
            if(right>0){
                DFS(left,right-1,res+")",result);
            }
        }
        
    }
};

Python 代码

思路跟C++差不多。

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res=[]
        output=[]
        self.dfs(n,n,res,output)
        return output

    def dfs(self,left, right, res, output):
        if(left>right):
            return 
        if left==0 and right==0:
            output.append("".join(res))
        else:
            if(left>0):
                res.append('(')
                self.dfs(left-1,right,res,output)
                res.pop(-1)
            if right>0:
                res.append(')')
                self.dfs(left,right-1,res,output)
                res.pop(-1)
        return output

参考文献

[Leetcode] generate parentheses 生成括号

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值