[LeetCode] Generate Parentheses

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) {
        vector<string> res;
        char *str = new char[(2*n)+1];
        str[2*n] = '\0';
        generate(res, str, 0, 0, 2*n);
        return res;
    }
    
    void generate(vector<string>& res, char *str, int left, int cur, int n) {
        if (left == 0 && cur == n) {
            res.push_back(str);
            return ;
        }
        if (left == 0) {
            str[cur] = '(';
            generate(res, str, 1, cur+1,n);
        } else {
            if (left + cur < n) {
                str[cur] = '(';
                generate(res, str, left+1, cur+1, n);           
            }
            str[cur] = ')';
            generate(res, str, left-1, cur+1,n);
        }
    }
};

猜你喜欢

转载自cozilla.iteye.com/blog/1869872