Generate Parentheses

来源:互联网 发布:数据库实施工程师 编辑:程序博客网 时间:2024/05/17 03:20

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:
    void helper(vector<string> & solution, string & singleSolution,
                int numofleft, int numofright, int n){
        if (singleSolution.size()==2*n)
            solution.push_back(singleSolution);
        else{
            if (numofleft<n){
                singleSolution += '(';
                helper(solution, singleSolution, numofleft+1, numofright, n);
                singleSolution = singleSolution.substr(0, singleSolution.size()-1);
            }
            
            if (numofright<numofleft){
                singleSolution += ')';
                helper(solution, singleSolution, numofleft, numofright+1, n);
                singleSolution = singleSolution.substr(0, singleSolution.size()-1);
            }
        }
    }


    vector<string> generateParenthesis(int n) {
        vector<string> solution;
        string singleSolution = "";
        helper(solution, singleSolution, 0, 0, n);
        
        return solution;
    }
};
0 0
原创粉丝点击