原问题连接 https://leetcode.com/problems/generate-parentheses/
符合该问题的解需要满足一个原则:在某个位置k前,左括号的个数大于等于右括号的个数。
具体可以分为以下三种情况:
(1)剩余左括号的个数和剩余右括号的个数都为0,组成一个合法的结果;
(2)剩余左括号的个数大于0,可以插入左括号;
(3)剩余右括号的个数大于0,并且剩余左括号的个数小于剩余右括号的个数,那么可以插入右括号;
具体实现代码如下:
vector<string> generateParenthesis(int n) {
vector<string> result;
string temp = "";
if (n <= 0)
return result;
generateParenthesisHelper(n, n, temp, result);
return result;
}
void generateParenthesisHelper(int leftNum, int rightNum, string temp, vector<string> &result)
{
if (leftNum == 0 && rightNum == 0)
{
result.push_back(temp);
return;
}
if (leftNum > 0)
{
generateParenthesisHelper(leftNum - 1, rightNum, temp + '(', result);
}
if (rightNum > 0 && leftNum < rightNum)
{
generateParenthesisHelper(leftNum, rightNum - 1, temp + ')', result);
}
}