leetcode-22-generate parentheses

Problem Description:

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

题目大意:

给定一个数字,返回该数字对括号能产生的所有合法括号组合。

Solutions:

使用回溯法,生成所有组合。

Code in C++:

class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> res;
            string tem;
            helper(res,tem,0,0,n);
            return res;

        }
        void helper(vector<string>&res,string& s,int left,int right,int n)
            {
                if(left==n&&right==n) {res.push_back(s);}

                if(left<n) {s.push_back('('); helper(res,s,left+1,right,n);s.pop_back();}
                if(right<left) {s.push_back(')'); helper(res,s,left,right+1,n);s.pop_back();}

            }
};