题目描述
给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()()()", "()(())",
示例1
输入
1
输出
["()"]
class Solution {
public:
/**
*
* @param n int整型
* @return string字符串vector
*/
void dfs(vector<string> &res, int left, int right, string cur){
if(left ==0 && right==0)
res.push_back(cur);
if(left>0)
dfs(res, left-1, right, cur+'(');
if(right>0 && right>left)
dfs(res, left, right-1,cur+')');
}
vector<string> generateParenthesis(int n) {
// write code here
vector<string> res;
if(n<1) return res;
string cur = "";
dfs(res, n, n, cur);
return res;
}
};