22. 括号生成
思路:递归,先生成左端的括号,之后在生成右段的括号,合成一个完整的括号并加入数组中。
class Solution {
public:
void backtrack(vector<string> &ans,string cur,int open,int close,int max)
{
if(cur.length() == max*2){
ans.push_back(cur);
return;
}
if(open<max)
backtrack(ans,cur+"(",open+1,close,max);
if(close<open)
backtrack(ans,cur+")",open,close+1,max);
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
backtrack(ans,"",0,0,n);
return ans;
}
};