给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
解答(C++):
class Solution { public: vector<string> vec; void backTrace(string str, int left, int right, int max){ if (str.size() == 2*max) { vec.push_back(str); return; } if (left < max) { backTrace(str+'(', left+1, right, max); } if (right < left) { backTrace(str+')', left, right+1, max); } } vector<string> generateParenthesis(int n) { backTrace("", 0,0,n); return vec; } };