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: Two methods are introduced here, one is recursive construction and the other is DFS.
1. Recursive method
This method is simple and straightforward, but to understand how it is constructed, n pairs of valid parentheses can be constructed by means of I (0=< I <= n-1) to the effective bracket pair inner and n-1-i to the effective bracket pair outer, "(" +inner+ ")" +outer, and no duplicates.
classSolution { Public: Vector<string> Generateparenthesis (intN) {if(n = =0)returnvector<string> (1,""); if(n = =1)returnvector<string> (1,"()"); Vector<string>result; for(inti =0; I < n; i++){ for(Auto Inner:generateparenthesis (i)) for(Auto Outer:generateparenthesis (n1-i)) Result.push_back ("("+ Inner +")"+outer); } returnresult; }};
2. You can also use DFS solver to always guarantee the number of "(" greater than or equal to ") during the build process.
classSolution { Public: Vector<string> Generateparenthesis (intN) {vector<string>result; if(N >0) Generate (N,"",0,0, result); returnresult; } voidGenerateintNstringSintLintR, vector<string> &result) { if(L = =N) {result.push_back (S.append (n-R,')')); return; } generate (n, S+'(', L +1, R, result); if(L > R) Generate (n, S +")", L, R +1, result); }};
Leetcode:generate parentheses