class Solution { public: /** * * @param n int整型 * @return string字符串vector */ void backtrack(vector<string>& res, string& cur, int open, int close, int n) { if(cur.size() == n * 2) { // 如果cur有2n个元素,即n对括号全部入队 res.push_back(cur); return; } if(open < n) { // 当左括号入队数量不超过n,将左括号入队,同时将open+1, cur.push_back('('); backtrack(res, cur, open + 1, close, n); cur.pop_back(); // 返回原来状态 } if(close < open) { // 当右括号数小于左括号数时,将右括号入队 cur.push_back(')'); backtrack(res, cur, open, close + 1, n); cur.pop_back(); // 返回原来状态 } } vector<string> generateParenthesis(int n) { // write code here vector<string> res; // 最后结果 string current; // 当前排序情况 backtrack(res, current, 0, 0, n); return res; } };