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();
}
}
};