题目:给定n对括号,编写一个函数来生成格式正确的括号的所有组合。
示例:
n = 3时,输出应该为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路:通过递归实现,具体看代码
class Solution {
public:
void generateP(int left,int right,string temp,vector<string> &res)
{
if(left > right)return;
if(left == 0 && right == 0)
res.push_back(temp);
if(left > 0)
generateP(left-1,right,temp+'(',res);
if(right > 0)
generateP(left,right-1,temp+')',res);
}
vector<string> generateParenthesis(int n) {
vector<string> res;
generateP(n,n,"",res);
return res;
}
};