https://leetcode.com/problems/generate-parentheses/
递归,用两个指标left和right来标记出合法规则,之后再left和right都达到n后,满足了可以输出的条件
此时,就可以把这个string压入到res中了。
1 class Solution { 2 public: 3 void getElement(int left,int right,vector<string>& res,string str,int n) 4 { 5 if(left==n&&right==n) 6 { 7 res.push_back(str); 8 return ; 9 } 10 else if(left==right) 11 { 12 getElement(left+1,right,res,str+"(",n); 13 } 14 else{ 15 if(left+1<=n) 16 getElement(left+1,right,res,str+"(",n); 17 if(right+1<=n) 18 getElement(left,right+1,res,str+")",n); 19 } 20 } 21 vector<string> generateParenthesis(int n) { 22 vector<string> res; 23 string str=""; 24 getElement(0,0,res,str,n); 25 return res; 26 27 } 28 };