一、题目
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: [“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
Example 2:
Input: n = 1
Output: [“()”]
Constraints:
1 <= n <= 8
二、题解
class Solution {
public:
vector<string> res;
void bracktracking(string& cur,int left,int right,int n){
if(cur.size() == n * 2) res.push_back(cur);
if(left < n){
cur.push_back('(');
bracktracking(cur,left+1,right,n);
cur.pop_back();
}
if(right < left){
cur.push_back(')');
bracktracking(cur,left,right+1,n);
cur.pop_back();
}
}
vector<string> generateParenthesis(int n) {
string cur;
bracktracking(cur,0,0,n);
return res;
}
};