Generate Parentheses Combinations with DFS

Day - 62 Generate Parentheses The problem - Given n pairs of parentheses, generate all combinations of well formed parentheses. Example : n = 3 → ["((()))","(()())","(())()","()(())","()()()"] Brute Force - Generate all 2^(2n) combinations, then filter for valid ones, still exponential. Approach Used - •) Initialize: Call DFS(0, 0, "", n, res) (start with 0 open, 0 close, empty string). •) DFS(openP, closeP, s, n, res), 1 - Base case, if openP == closeP == n: add s to res (valid combination) and return. 2 - Recursive First case, if openP < n: add '(', recurse with openP+1. 3 - Recursive Second case, if closeP < openP: add ')', recurse with closeP+1. Complexity - Time - O(4^n / √n), the number of valid combinations. Space - O(n), recursion depth. Note - Track open and close parentheses count. Add '(' if open < n, add ')' if close < open. Recurse until both equal n. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories