生成括号 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。C++

核心是必须要先有一个左括号才能给字符串添加括号,且无论何时右括号的个数一定要小于等于左括号的个数

而且函数参数最好不要使用引用,方便临时变量的赋值。

C++代码如下


class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        if(n<=0)
            return res;
        //肯定要先定义一个左括号
        int zuo=0,you=0;//左括号的个数为0,但肯定是先有左括号
        shengcheng(res,"(",n,1,0);
        return res;
    }
    void shengcheng(vector<string> &res,string out,int index,int zuo,int you)
    {
        if(you>zuo||zuo>index||you>index)
        {
            return;
        }
        
        if(zuo==you&&zuo==index)
        {
            res.push_back(out);
        }
        else
        {
            shengcheng(res,out+'(',index,zuo+1,you);
            shengcheng(res,out+')',index,zuo,you+1);  
        }                
    }
};

猜你喜欢

转载自blog.csdn.net/u011526967/article/details/82961538