shriyanshi24jindal

Generate Parentheses

Mar 30th, 2026
159
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 4.83 KB | None | 0 0
  1. class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. List<String> result = new ArrayList<>();
  4. // no of opening and closing brackets
  5. int open = n;
  6. int close = n;
  7. findBalancedParenthesis(open, close, result, "");
  8. return result;
  9. }
  10.  
  11. public void findBalancedParenthesis(int open, int close, List<String> result, String temp)
  12. {
  13. // base condition: when both opening and closing brackets is finished, so valid string
  14. if(open == 0 && close == 0)
  15. {
  16. result.add(temp);
  17. return;
  18. }
  19.  
  20. // choice of opening bracket
  21. if(open != 0)
  22. {
  23. findBalancedParenthesis(open-1, close, result, temp + '(');
  24. }
  25.  
  26. // choice of closing bracket
  27. if(close > open)
  28. {
  29. findBalancedParenthesis(open, close-1, result, temp + ')');
  30. }
  31. }
  32. }
RAW Paste Data Copied