LeetCode_Generate Parentheses

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:
 
"((()))", "(()())", "(())()", "()(())", "()()()"

  backtracking solution:

复制代码
class Solution {
private :
    int n;
    vector<string> result;
public:
   
    vector<string> generateParenthesis(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        rs.clear() ;
        if(n <1 ) return  rs;
        this.n = n;
        string s;
        
        backtracking(s,0,0);
        
        return result ;
        
    }
    void backtracking(string path, int left, int right)
    {
      if(left > n || right > n) return ;
      
      if(path.size() == 2*n )
             result.push_back(path);
             
       if(left+1 <= n)
           backtracking(path+'(', left+1, right );
       if(right+1<= left)
           backtracking(path+')',left, right+1) ;
    
    }



};
复制代码

 

posted @   冰点猎手  阅读(207)  评论(0编辑  收藏  举报
编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· AI Agent爆火后,MCP协议为什么如此重要!
· dotnet 源代码生成器分析器入门
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
· ASP.NET Core 模型验证消息的本地化新姿势
· Java使用多线程处理未知任务数方案
点击右上角即可分享
微信分享提示