Skip to main content

Generate Parentheses

Learn Generate Parentheses (Recursion & Backtracking, Data Structures & Algorithms) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

All Valid Combinations of N Pairs Generate every well-formed combination of N pairs of parentheses. Track two counts as you build the string: open used so far, close used so far. Add '(' whenever open < n ; add ')' only when close < open (never more closes than opens at any point - that's what makes a prefix valid).

More lessons in Recursion & Backtracking