Problems178
Search for a command to run...
Initialization
Track how many '(' and ')' are still available. An open bracket can be added whenever any remain; a close bracket only while more closes remain than opens — exactly the condition that keeps the prefix balanced.
Backtracking
1function generateParenthesis(n) {2 const results = [];3 generate('', n, n, results);//n: 3ans: []4 return results.sort();5}6 7function generate(current, open, close, results) {8 // Base case: nothing left to place9 if (open === 0 && close === 0) {10 results.push(current);11 return;12 }13 14 // An open bracket is always safe while any remain15 if (open > 0) {16 generate(current + '(', open - 1, close, results);17 }18 19 // A close bracket is safe only while closes outnumber opens20 if (close > open) {21 generate(current + ')', open, close - 1, results);22 }23}