Monday, November 25, 2013

LeetCode Problem : Generate Parentheses

Problem

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:
"((()))", "(()())", "(())()", "()(())", "()()()"

Code

void gp_r(string& out,vector<string>& result,int n1,int n2,int pos)
{
    if(n1 == 0 && n2 == 0){
        result.push_back(out);
        return;
    }
    if(n1 == n2){
        out[pos] = '(';
        gp_r(out,result,n1-1,n2,pos+1);
    }
    else{
        if(n1 > 0){
            out[pos] = '(';
            gp_r(out,result,n1-1,n2,pos+1);
        }
        out[pos] = ')';
        gp_r(out,result,n1,n2-1,pos+1);
    }
}
vector<string> generateParenthesis(int n) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    vector<string> result;
    string out;
    out.resize(2*n);
    gp_r(out,result,n,n,0);
    return result;
}

No comments:

Post a Comment