Fork me on GitHub

Leetcode22.Generate Parentheses括号生成

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

例如,给出 n = 3,生成结果为:

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

 

 

class Solution {
public:
    vector<string> res;
    vector<string> generateParenthesis(int n)
    {
        if(n == 0)
            return res;
        DFS("", n, n);
        return res;
    }


    //必须满足right >= left
    void DFS(string str, int left, int right)
    {
        if(left == 0 && right == 0)
        {
            res.push_back(str);
            return ;
        }
        char c = 0;
        if(left == right)
        {
            c = '(';
            DFS(str + c, left - 1, right);
        }
        else
        {
            for(int i = 0; i < 2; i++)
            {
                if(i == 0 && left > 0)
                {
                    c = '(';
                    DFS(str + c, left - 1, right);
                }
                else if(i == 1 && right > 0)
                {
                    c = ')';
                    DFS(str + c, left, right - 1);
                }
            }
        }
    }
};

 

posted @ 2018-11-17 18:51  lMonster81  阅读(89)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */