1 回溯法
代码语言:javascript
复制class Solution {
private:
vector<string> solution;
string path = "";
public:
void backtrack(int len, int left, int right, int n) {
if (len == n * 2) {
solution.push_back(path);
return;
}
// 左括号数量 < n (当n=3时,括号数量为6,则左括号数量需在2或以下)
if (left < n) {
path.push_back('(');
backtrack(len 1, left 1, right, n);
path.pop_back();
}
// 右括号数量 < 左括号数量 (当n=3时,设左括号数量为2,则右括号数量需在2或以下)
if (right < left) {
path.push_back(')');
backtrack(len 1, left, right 1, n);
path.pop_back();
}
}
vector<string> generateParenthesis(int n) {
backtrack(0, 0, 0, n);
return solution;
}
};