数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且有效的括号组合。
思路:递归列出每一种可能,在一个位置,如果可以放左括号,就放左括号;可以放右括号,就放右括号;都可以放,就两种情况都试一次。虽然是动态规划分类下的,但是不知道用动态规划怎么做
vector<string> generateParenthesis(int n) {
vector<string>res;
helper(res,"",n,0);
return res;
}
void helper(vector<string>&res,string str,int n,int m){
if(n==0&&m==0){
res.push_back(str);
return;
}
if(n>0)helper(res,str+'(',n-1,m+1);
if(m>0)helper(res,str+')',n,m-1);
}