Generate Parentheses
Q:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
A: DFS问题。
void generate_aux(int leftcount,int rightcount,string path,vector<string>& result)
{
if(leftcount==0&&rightcount==0) //左右括号都加上去了。
{
result.push_back(path);
return;
}
if(leftcount>0)
generate_aux(leftcount-1,rightcount,path+"(",result); //如果左括号还有,那么肯定可以先加上左括号。
if(leftcount<rightcount)
generate_aux(leftcount,rightcount-1,path+")",result); //只有当已经加上的左括号大于右括号数时,才能继续加右括号。
}
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> result;
if(n<=0)
return result;
generate_aux(n,n,"",result);
return result;
}
浙公网安备 33010602011771号