Topic:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
Thinking Analysis:
The final combination results always have the same rule: the number of opening parentheses is greater than or equal to the number of closing parentheses. So, according to this rule: suppose that the left parenthesis and right parenthesis are left in position K, and if left>0, the opening parenthesis can be printed directly. , if Left<right and right!=0, you can print the closing parenthesis. If both left and right are zero, then a legal arrangement has been completed to print it out.
C + + Reference code:
classsolution{Private:voidGeneratesub ( vector<string>&result,stringCurrentintLeftintright) {if(left = =0&& right = =0) Result.push_back (current);Else{if(Left! =0) generatesub (result, current +' (', left-1, right);if(Left < right && right! =0) generatesub (result, current +' ) ', left, right-1); } } Public: vector<string>Generateparenthesis (intN) { vector<string>Resultif(N >0) Generatesub (Result,string(), n, N);returnResult }};
C # Reference Code:
Public classsolution{Private void generatesubstring(ilist<string> result,stringCurrentintLeftintright) {Stringvalue= current;if(left = =0&& right = =0) result. ADD (value);Else{if(Left! =0) generatesubstring (result, current +' (', left-1, right);if(Left < right && right! =0) generatesubstring (result, current +' ) ', left, right-1); } } Publicilist<string>generateparenthesis(intN) {ilist<string> result =Newlist<string> ();if(N >0) generatesubstring (Result,"", N, N);returnResult }}
Leetcode:generate parentheses