Generate parentheses
GivenNPairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, givenN= 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Algorithm ideas:
DFS: For each bit, try the suffix '(' or ')', use K to record the number of left parentheses, and use couple to record the matched logarithm. Pay attention to pruning.
This code is the most concise algorithm I have seen: [leetcode] generate parentheses
The Code is as follows:
1 public class solution {2 list <string> result = new arraylist <string> (); 3 public list <string> generateparenthesis (int n) {4 DFS (New stringbuilder (), 0, 0, n); 5 return result; 6} 7 private void DFS (stringbuilder Sb, int K, int couple, int N) {8 If (k = 0 & couple = N & SB. length () = 2 * n) {9 result. add (sb. tostring (); 10 return; 11} 12 if (k <0 | sb. length ()> 2 * n) return; // pruning 13 char [] C = {'(', ')'}; 14 for (INT I = 0; I <2; I ++) {15 k = (I = 0 )? K + 1: K-1; 16 if (k> 0 & I = 1) {// the premise of pairing is k> 0, 17 couple ++; 18 k --; 19} 20 if (k <0) {// if there are left brackets in front of the wood, only 21 k ++; 22 continue; 23} 24 DFS (sb. append (C [I]), K, couple, n); 25 sb. deletecharat (sb. length ()-1); 26} 27} 28}