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;
        if( n == 0)
            return res;
        core( res, "", n, 0, 0);
        return res;
    }
    void core( vector< string> &res, string cur, int n, int left, int right){
        if( right == n){
            res.push_back(cur);
            return;
        }
        if( left < right || left > n || right > n)
            return;
        else if( left == right){
            core( res, cur+'(', n, left+1, right);
        }
        else{
            core( res, cur+'(', n, left+1, right);
            core( res, cur+')', n, left, right+1);
        }
    }
};
点赞