题目链接:https://leetcode-cn.com/problems/generate-parentheses/
题目如下:
class Solution {
public:
vector<string> generateParenthesis(int n) {
//结论1、任意前缀中,'('的数量>=')'的数量
//结论2、左右括号数量相等
backtracking(n,0,0);
return res;
}
void backtracking(int n,int L,int R){
if(path.size()==n*2){//n对括号,长度一共为n*2
res.push_back(path);
return;
}
if(L<n){ //'('放入的条件: '('的数量 <= n
path.push_back('(');
backtracking(n,L+1,R);
path.pop_back();
}
if(R<L){ //')'放入的条件: '('的数量 >= ')'的数量
path.push_back(')');
backtracking(n,L,R+1);
path.pop_back();
}
}
private:
vector<string> res;
string path="";
};