题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串vector */ string left = "("; string right = ")"; vector<string> res; void pro(int n, int x, int y, string str, int num) { if (y > x) return; if (x == y && x + y == 2*n) { if(std::find(res.begin(), res.end(), str) == res.end()) res.push_back(str); } if (x + y < 2*n) { if (x <= y) { pro(n, x + 1, y, (str + left), num - 1); } else if (x > y) { if (x < n) { pro(n, x + 1, y, str + left, num - 1); } pro(n, x, y + 1, str + right, num - 1); } } } vector<string> generateParenthesis(int n) { // write code here // 只要每时每刻满足左边括号的数目是大于右边括号的数目即可 string str; pro(n, 0, 0, str, 2*n); return res; } };