您的位置:首页 > 其它

LeetCode: Generate Parentheses

2012-11-29 14:45 453 查看
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lp = n;
int rp = n;
vector<string> res;
string str = "";
generate(res, str, lp, rp);
return res;
}
void generate(vector<string> &res, string str, int lp, int rp){
if(lp == 0 && rp == 0){
res.push_back(str);
return;
}
string temp = str;
if(lp > 0){
temp+="(";
generate(res, temp, lp -1, rp);
}
temp = str;
if(rp > lp){
temp += ")";
generate(res, temp, lp, rp - 1);
}
return;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: