[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:
    void func(vector<string> &res,string ans,int left,int right)
    {
        if(left==0&&right==0)
        {
            res.push_back(ans);
            return;
        }
        if(left>0) func(res,ans+'(',left-1,right+1);
        if(right>0) func(res,ans+')',left,right-1);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string ans="";
        func(res,ans,n,0);
        return res;
    }
};

  

posted @ 2013-11-11 17:59  七年之后  阅读(192)  评论(0编辑  收藏  举报