这道题考虑用递归算法。截至条件是剩余的左括号和右括号数都为0,在递归时注意剩余的左括号数要小于右括号数。实现代码如下:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if (n < 1)return res;
helper(res, "", n, n);
return res;
}
void helper(vector<string> &v, string str, int left, int right)
{
if (left == 0 && right == 0)
{
v.push_back(str);
return;
}
if (left > 0)
{
helper(v, str + "(", left - 1, right);
}
if (right > 0 && left < right)
{
helper(v, str + ")", left, right - 1);
}
}
};