题目链接:https://leetcode-cn.com/problems/generate-parentheses/
题目描述:
题解:
当n = 3 时,字符串长度为6,left = 3, right = 3。当左括号个数大于右括号时,不会产生合法组合。
class Solution {
public:
vector<string> ans;
vector<string> generateParenthesis(int n) {
string path = "";
trackingback(n, n, path);
return ans;
}
void trackingback(int left, int right, string path)
{
//如果左右括号个数均为0,则生成了合法组合
if(left == 0 && right == 0)
{
ans.push_back(path);
return;
}
if(left < 0 || right < 0)
return;
//如果可使用的左括号个数 > 可使用的右括号个数,则不能产生合法组合
if(left > right)
return;
//添加左括号
if(left > 0)
{
path.push_back('(');
trackingback(left - 1, right, path);
path.pop_back();
}
//添加右括号
if(right > 0)
{
path.push_back(')');
trackingback(left, right - 1, path);
path.pop_back();
}
}
};