题目
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路
采用递归法
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> resultStr;
string curStr;
int open = 0, close = 0;
backtrack(resultStr, curStr, open, close, n);
return resultStr;
}
void backtrack(vector<string>&resultStr, string &curStr,
int open, int close, int max)
{
if (curStr.size() == max * 2)
{
resultStr.push_back(curStr);
return;
}
if (open < max)
backtrack(resultStr, curStr + "(", (open + 1), close, max);
if (close < open)
backtrack(resultStr, curStr + ")", (open), close + 1, max);
}
};
int main(int argc, char* argv[])
{
vector<string> result;
int n = 3;
result = Solution().generateParenthesis(3);
system("pause");
return 0;
}