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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Analysis
is obviously a traversal process, but how to traverse is a problem. Traversal, we can often use recursion to solve. Recursion, the routine is to write out the conditions first, and then write the other recursive calling program part. the exit condition of this topic is obviously when the left parenthesis (and the closing parenthesis) are all used up, the results are pressed back in. What about the rest of it? This time will be combined with specific problems, specific analysis. parentheses match the core, the resulting parentheses must be well-formed. This requires the currently generated cur string, so be sure that the number of opening parentheses is less than the number of closing parentheses. Therefore, if the number of opening brackets m is not equal to 0, you can continue placing, and when the number of opening parentheses is less than the number of closing brackets, and the number of closing parentheses is not equal to 0, the closing parenthesis can be placed!
Code
Running time: 5ms
Class Solution {public: vector<string> generateparenthesis (int n) { vector<string> res; if (n = = 0) return res; String cur = ""; Fun (res, cur, n, n); return res; } void Fun (vector<string>& res, string cur, int m, int n) { if (m = = 0 && n = = 0) { res . push_back (cur); return; } if (M! = 0) {fun (res, cur + ' (', m-1, n); } if (M < n && n! = 0) //"M < n" Ensure the generated parantheses is well-formed {fun (res, CU R + ') ', M, n-1);}} ;
Generate parentheses--Problem Solving report