Thursday, May 16, 2013

Leetcode: Generate Parentheses in C++



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

void help(int n, int left, int right, string cur,vector<string>& result )
    {
        string tmp;
        if(right==n)
        result.push_back(cur);
        if(left<n)
        {
            tmp=cur+"(";
            help(n, left+1, right, tmp, result);
        }
        if(left>right)
        {
            tmp = cur+")";
            help(n, left, right+1, tmp, result);
        }
    }
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string cur = "";
        help(n, 0, 0, cur, result);
        return result;
    }

No comments:

Post a Comment