您的位置:首页 > 其它

LeetCode | Generate Parentheses

2016-08-19 11:29 369 查看
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:

[

“((()))”,

“(()())”,

“(())()”,

“()(())”,

“()()()”

]

简单来讲就是括号匹配的问题,给定一个n,给出所有可能的括号匹配解。

递归结束条件是step==n 或者左括号的数量小于右括号

class Solution {
public:
int n,rawN;
vector<string> generateParenthesis(int n) {
vector<string> result;
string temp;
this->n=2*n;this->rawN=n;
generate(temp,0,0,0,result);
return result;
}

void generate(string &temp,int step,int leftCount,int rightCount,vector<string> &result){
//递归终点
if(step==n){
result.push_back(temp);
return;
}
if(step>0&& leftCount<rightCount) return;

//还可以添加(
if(leftCount<rawN){
temp=temp+'(';
generate(temp,step+1,leftCount+1,rightCount,result);
temp.pop_back();
}
//还可以添加)
if(rightCount<rawN){
temp=temp+')';
generate(temp,step+1,leftCount,rightCount+1,result);
temp.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: