From 78f843c379ebf486e543c081077f413ca7b046bf Mon Sep 17 00:00:00 2001 From: c99SRS Date: Sat, 14 Oct 2023 20:04:25 +0530 Subject: [PATCH] added parenthesis qns --- Coding/GenerateParentheses.java | 67 +++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Coding/GenerateParentheses.java diff --git a/Coding/GenerateParentheses.java b/Coding/GenerateParentheses.java new file mode 100644 index 00000000..ff9a8797 --- /dev/null +++ b/Coding/GenerateParentheses.java @@ -0,0 +1,67 @@ +/* +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 + +*/ + +class Solution { + + List ansList = new ArrayList(); + public List generateParenthesis(int n) { + + StringBuilder curr = new StringBuilder(); + + + generate(curr,0,0,n); + + return ansList; + } + + void generate(StringBuilder curr,int openCount,int closedCount, int n){ + + + if(openCount == n && closedCount == n){ + ansList.add(curr.toString()); + return; + } + + if(openCount > n || closedCount > n) + return; + + + // choice 1 + if(openCount < n){ + curr.append("("); + generate(curr, openCount+1, closedCount, n); + curr.deleteCharAt(curr.length()-1); + } + + // choice 2 + if(openCount > closedCount){ + curr.append(")"); + generate(curr, openCount, closedCount+1, n); + curr.deleteCharAt(curr.length()-1); + } + + return; + } + + } \ No newline at end of file