Last active
January 25, 2023 13:21
-
-
Save alvindera97/d40157428f44ff80bcbc26bf1e0734f7 to your computer and use it in GitHub Desktop.
Backtracking Solution For LeetCode 22 (Generate Parenthesis)
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 generateParenthesis(n) { | |
result = new Array(); | |
const backtrack = (op, cp, path = "", stack = new Array()) => { | |
if (op < 0 || cp < 0) { | |
return; | |
} | |
if (stack.length > 1 && stack.at(-1) === ")" && stack.at(-2) === "(") { | |
stack = stack.slice(0, stack.length - 2); | |
} | |
if (op === 0 && cp === 0 && stack.length === 0) { | |
result.push(path); | |
return; | |
} | |
if (op === cp === 0 && stack.length !== 0) { | |
return; | |
} | |
if (path.length === 0) { | |
return backtrack(op - 1, cp, path + "(", [...stack, "("]); | |
} | |
backtrack(op - 1, cp, path + "(", [...stack, "("]) | |
backtrack(op, cp - 1, path + ")", [...stack, ")"]) | |
}; | |
backtrack(n, n); | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment