Generate Parentheses
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; if(n>0){ generate(n,"",0,0,res); } return res; } //采用递归树的思想,当左括号数大于右括号数时可以加左或者右括号,否则只能加左括号,当左括号数达到n时,剩下全部加右括号。 void generate(int n,string s,int lf,int rg,vector<string> &res){ if(lf==n){//only can add ')' res.push_back(s.append(n-rg,')')); return; } generate(n,s+'(',lf+1,rg,res);//add '(' if(lf>rg){ generate(n,s+')',lf,rg+1,res);//add ')' } } };
class Solution { public: void help(int n,int x,int y,string now,vector<string> &answer){//dfs if(y==n){ answer.push_back(now); return; } if(x<n){ help(n,x+1,y,now+"(",answer);//加入左括号 } if(x>y){ help(n,x,y+1,now+")",answer);//加入右括号 } } vector<string> generateParenthesis(int n) { vector<string> answer; help(n,0,0,"",answer); return answer; } };
struct node{ int x,y; string now; }; class Solution { public: void help(int n,vector<string> &answer){//bfs if(n==0){ answer.push_back(""); return; } node start,tmp; start.x=start.y=0; start.now=""; queue<node> q; for(q.push(start);!q.empty();q.pop()){ tmp=q.front(); node other; if(tmp.x<n){ other.x=tmp.x+1; other.y=tmp.y; other.now=tmp.now+"("; q.push(other); } if(tmp.x>tmp.y){ other.x=tmp.x; other.y=tmp.y+1; other.now=tmp.now+")"; if(other.y==n){//组合成功 answer.push_back(other.now); }else{ q.push(other); } } } } vector<string> generateParenthesis(int n) { vector<string> answer; help(n,answer); return answer; } };