生成所有的由n对括号组成的合法组合
1. 递归recursion(0,0,temp,res,n); 记录左右括号的数量
2. 终止条件 左右括号使用数量达到n 全用玩了
3. 递归过程:
//使用一次左括号
if(left < n) recursion(left + 1, right, temp + "(", res, n);
//使用右括号个数必须少于左括号
if(right < n && left > right) recursion(left,right+1,temp + ")",res,n);
#include <mutex>
class Solution {
public:
/**
*
* @param n int整型
* @return string字符串vector
*/
void recursion(int left, int right,string temp,vector<string> &res,int n){
//左右括号都用完了,就加入结果
if(left == n && right == n){
res.push_back(temp);
return ;
}
//使用一次左括号
if(left < n)
recursion(left + 1, right, temp + "(", res, n);
//使用右括号个数必须少于左括号
if(right < n && left > right)
recursion(left,right+1,temp + ")",res,n);
}
vector<string> generateParenthesis(int n) {
// write code here
//记录结果
vector<string> res;
//记录每次组装的字符串
string temp;
//递归
recursion(0,0,temp,res,n);
return res;
}
};