Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created May 4, 2023 21:51
Show Gist options
  • Select an option

  • Save optimistiks/5ac71a3dd55c99b8ad40ff672994f80b to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/5ac71a3dd55c99b8ad40ff672994f80b to your computer and use it in GitHub Desktop.
For a given number, n, generate all combinations of balanced parentheses.
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