Created
May 4, 2023 21:51
-
-
Save optimistiks/5ac71a3dd55c99b8ad40ff672994f80b to your computer and use it in GitHub Desktop.
For a given number, n, generate all combinations of balanced parentheses.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function generateCombinationsRec(n, numOpen, numClosed, combo, result) { | |
| // base case - length of the combination is n * 2 | |
| if (combo.length === n * 2) { | |
| result.push(combo); | |
| return; | |
| } | |
| // can we add an opening bracket to the current combination? | |
| // yes if number of opening brackets in the combination is less than n | |
| // so we add it, and pass it further to add more brackets, incrementing numOpen | |
| if (numOpen < n) { | |
| generateCombinationsRec(n, numOpen + 1, numClosed, `${combo}(`, result); | |
| } | |
| // can we also add a closing bracket? | |
| // yes if number of closing brackets is less than open brackets | |
| // add it and pass further | |
| if (numClosed < numOpen) { | |
| generateCombinationsRec(n, numOpen, numClosed + 1, `${combo})`, result); | |
| } | |
| } | |
| export function generateCombinations(n) { | |
| const result = []; | |
| generateCombinationsRec(n, 0, 0, "", result); | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
