n || right > left) return; else if (left == n && right == n) { res.push_back(str); } else { dfs(str + "(", left + 1, right); dfs(str + ")", left, right + 1); } } };"> n || right > left) return; else if (left == n && right == n) { res.push_back(str); } else { dfs(str + "(", left + 1, right); dfs(str + ")", left, right + 1); } } };"> n || right > left) return; else if (left == n && right == n) { res.push_back(str); } else { dfs(str + "(", left + 1, right); dfs(str + ")", left, right + 1); } } };">
class Solution {
public:
int n;
vector<string> res;
vector<string> generateParenthesis(int n) {
this->n = n;
dfs("", 0, 0);
return res;
}
void dfs(string str, int left, int right) {
if (left > n || right > left) return;
else if (left == n && right == n) {
res.push_back(str);
} else {
dfs(str + "(", left + 1, right);
dfs(str + ")", left, right + 1);
}
}
};
换一种,这次数量是括号剩余个数,可以不传参 int n
class Solution {
public:
vector<string> generateParenthesis(int n) {
dfs("", n, n);
return res;
}
private:
vector<string> res;
void dfs(const string& str, int left, int right) {
if (left < 0 || left > right) // 出现类似 ()) )) 这种格式都是错误的不用再继续了
return;
if (left == 0 && right == 0) {
res.push_back(str);
return;
}
dfs(str + '(', left - 1, right);
dfs(str + ')', left, right - 1);
}
};