1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include <iostream> #include <vector> #include <string> using namespace std;
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; string path; dfs(res, path, n, n); return res; }
void dfs(vector<string>& res, string path, int lc, int rc) { if (lc == 0 && rc == 0) { res.push_back(path); }
if (lc > 0) { dfs(res, path+'(', lc-1, rc); } if (rc > 0 && lc < rc) { dfs(res, path+')', lc, rc-1); } } };
class Solution_1 { public: vector<string> generateParenthesis(int n) { vector<string> res; string path; dfs(res, path, n, n);
return res; }
void dfs(vector<string>& res, string& path, int left, int right) { if (left > right) { return; } if (left < 0 || right < 0) { return; } if (left == 0 && right == 0) { res.push_back(path); return; }
path.push_back('('); dfs(res, path, left-1, right); path.pop_back();
path.push_back(')'); dfs(res, path, left, right-1); path.pop_back(); } };
void printArray(const vector<string>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << "\"" << nums[i] << "\""; if (i != nums.size() - 1) cout << ","; } cout << "]" << endl; }
int main() { Solution solution; vector<int> n_cases = {3, 1};
for (int n : n_cases) { vector<string> result = solution.generateParenthesis(n);
cout << "Input: n = " << n << endl; cout << "Output: "; printArray(result); }
return 0; }
|