Skip to content

Commit d2b2623

Browse files
Added a backtracking solution for the generate paranthesis.
1 parent 1e8dcbd commit d2b2623

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Solution is based on the backtracking paradigm. The solution explores the entire solution
3+
* space for all the permutations that are possible. While making the permutations, it also
4+
* checks for the boundary conditions to see if the solution can be found in this path. If the
5+
* solution cannot be found, the solution space is backtracked and it is not explored further.
6+
*
7+
* Complexity: Time and Space O((4^n)/(n^(1/2)).
8+
* Refer https://leetcode.com/problems/generate-parentheses/solution/ for more details.
9+
*
10+
* @param n
11+
*/
12+
function generateParenthesis(n: number): string[] {
13+
const result: string[] = [];
14+
genHelper(n * 2, result);
15+
return result;
16+
};
17+
18+
function genHelper(n: number, result: string[], open: number = 0, close: number = 0, str: string = "") {
19+
20+
// Base Condition to terminate the recursion
21+
if (str.length >= n) {
22+
result.push(str);
23+
return;
24+
}
25+
26+
// Boundary conditions to validate if the backtracking is required, or we can proceed.
27+
if (open < n/2) {
28+
genHelper(n, result, open + 1, close, str + "(");
29+
}
30+
31+
// Boundary condition to validate the backtracking again if required, or we can proceed.
32+
if (open > close) {
33+
// 2nd condition validates if we have not added closing braces before the opening braces.
34+
genHelper(n, result, open, close + 1, str + ")");
35+
}
36+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy