——Generate Parentheses

22、Generate Parentheses

生成括號

給定 n 對括號,請寫一個函數以將其生成新的括號組合,並返回所有組合結果。

樣例

給定 n = 3, 可生成的組合如下:

"((()))", "(()())", "(())()", "()(())", "()()()"

分析:

1.排列組合問題,可以使用遞歸按順序添加括號,將所有可能列出(回溯法)
2.只有左括號多於右括號時才能添加左括號
3.左右括號都等於n時結束

代碼:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章