LeetCode, leetcodeoj
Link: Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))","(()())","(())()","()(())","() ()()"
The requirement for this question is to give n pairs of parentheses and generate all the correct combinations of parentheses.
The number of matching parentheses in the correct form should be generated. It is actually the catlan number, which is not detailed here.
Recursion can be used to output the correct combination of All parentheses. Use two variables, l and r, to record the number of left and right brackets. if and only if the left and right parentheses are 0, the end ends normally. Of course, there is another limit, that is, you can add the right parenthesis only when there are more left parentheses.
Time Complexity :??? (Number of results)
Spatial complexity :??? (Number of results)
1 class Solution 2 {3 private: 4 void generateParenthesis (vector <string> & v, string s, int l, int r) // l and r records the number of left and right parentheses 5 {6 if (l = 0 & r = 0) // when and only when the left and right parentheses are 0, normal end 7 v. push_back (s); 8 9 if (l> 0) 10 generateParenthesis (v, s + "(", l-1, r ); 11 if (r> 0 & l <r) // you can add the right brace 12 generateParenthesis (v, s + ")", l, r-1); 13} 14 public: 15 vector <string> generateParenthesis (int n) 16 {17 vector <string> v; 18 generateParenthesis (v, "", n, n); 19 return v; 20} 21 };
Reprinted, please describe the Source: LeetCode --- 22. Generate Parentheses