Skip to content

Instantly share code, notes, and snippets.

@QuadradS
Last active May 18, 2024 07:36
Show Gist options
  • Save QuadradS/58eb31e17ed53943ccc508b4f2306438 to your computer and use it in GitHub Desktop.
Save QuadradS/58eb31e17ed53943ccc508b4f2306438 to your computer and use it in GitHub Desktop.
Finished generate Parentheses
// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
// Example 1:
// Input: n = 3
// Output: ["((()))","(()())","(())()","()(())","()()()"]
// Example 2:
// Input: n = 1
// Output: ["()"]
// Constraints:
// 1 <= n <= 8
function generateParentheses(n) {
const result = [];
const stack = [{ current: '', openCount: 0, closeCount: 0 }];
while (stack.length > 0) {
const { current, openCount, closeCount } = stack.pop();
if (current.length === 2 * n) {
result.push(current);
continue;
}
if (openCount < n) {
stack.push({ current: current + '(', openCount: openCount + 1, closeCount });
}
if (closeCount < openCount) {
stack.push({ current: current + ')', openCount, closeCount: closeCount + 1 });
}
}
return result;
}
console.log(generateParentheses(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment