使用dfs
#include <iostream>
#include <vector>
using namespace std;
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);
}
dfs(str + '(', left - 1, right);
dfs(str + ')', left, right - 1);
}
};
int main() {
Solution test;
vector<string>ans= test.generateParenthesis(3);
for (int i = 0; i < ans.size();i++) {
cout << ans[i]<<endl;
}
return 0;
}