22. Generate Parentheses
Analysis
中午吃啥~—— [ummmm~]
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
递归实现~
Implement
class Solution {
public:
vector<string> generateParenthesis(int n) {
string tmp;
helper(n, 0, 0, tmp);
return res;
}
void helper(int n, int left, int right, string& tmp){
if(left == n && right == n){
res.push_back(tmp);
return ;
}
if(left < n){
tmp += "(";
helper(n, left+1, right, tmp);
tmp.pop_back();
}
if(right < left){
tmp += ")";
helper(n, left, right+1, tmp);
tmp.pop_back();
}
}
private:
vector<string> res;
};