Created
November 25, 2024 13:33
-
-
Save sAVItar02/106b7d105050fbc4ef2401ca70b91ea9 to your computer and use it in GitHub Desktop.
Generate Parentheses
This file contains 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
/** | |
* @param {number} n | |
* @return {string[]} | |
*/ | |
var generateParenthesis = function(n) { | |
let res = []; | |
function rec(open, close, string = "") { | |
if((open == close) && (open + close == 2*n)) { | |
res.push(string); | |
return; | |
} | |
if(open < n) { | |
rec(open+1, close, string + "("); | |
} | |
if(close < open) { | |
rec(open, close+1, string + ")"); | |
} | |
} | |
rec(0, 0, ""); | |
return res; | |
}; | |
// If Open < n ----> add open parentheses | |
// if close < open and open < n add either open parentheses or closed parentheses | |
// if close < open and open ! < n add closed parentheses | |
// if open == close and open == close == n ------> push string into res | |
// Time: O(2^n) | |
// Space: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment