解题思路:
如果左括号数量不大于 n,我们可以放一个左括号。如果右括号数量小于左括号的数量,我们可以放一个右括号。
总结:
1.左括号数量 <= n,
2.左括号数量 >= 右括号数量
3.左括号数量 + 右括号数量 = 2*n , 本次递归结束,返回。
class Solution {
public:
void DFS(vector<string>& ans ,string& str, int n , int left ,int right)
{
if(str.size() == 2*n) //数量够了,返回,加入结果集
{
ans.push_back(str);
return ;
}
if(left < n) // 左括号个数 <= n
{
str += '(';
DFS(ans , str , n ,left+1 ,right);
str.pop_back(); //回退
}
if(right < left) //左括号个数 >= 右括号个数
{
str += ')';
DFS(ans , str ,n ,left , right+1);
str.pop_back(); //回退
}
}
vector<string> generateParenthesis(int n)
{
vector<string> ans;
string str;
DFS(ans ,str , n , 0 , 0);
return ans;
}