您的位置:首页 > 其它

LeetCode OJ Generate Parentheses

2015-03-22 18:26 381 查看
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:

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

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        ans.clear();
        anAns.clear();
        numPair = n;
        makeParentheses(0, 0);
        return ans;
    }
    void makeParentheses(int numL, int numR) {
        if (numR == numPair) {  // once the number of right parentheses is equal to n, the string is one answer
            ans.push_back(anAns);
            return;
        }
        if (numL < numPair) {  // whenever the number of left parentheses is less than n, we can try to push one
            anAns.push_back('(');
            makeParentheses(numL + 1, numR);
            anAns.pop_back();
        }
        if (numR < numL) {  // whenever the number of right parentheses is less than left parentheses's, we can try to push one
            anAns.push_back(')');
            makeParentheses(numL, numR + 1);
            anAns.pop_back();
        }
    }
private:
    string anAns;
    vector<string> ans;
    int numPair;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: