1. 程式人生 > >生成括號 給出 n 代表生成括號的對數,請你寫出一個函式,使其能夠生成所有可能的並且有效的括號組合。C++

生成括號 給出 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);  
        }                
    }
};