Advertisement
Akshansh0Sharma

StringBuilder parenthesis

Apr 25th, 2024 (edited)
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class GeneratePaqrenthesis {
  4. static void solve(ArrayList<StringBuilder> output, int open, int close, StringBuilder ans){
  5. if(open == 0 && close == 0){
  6. output.add(new StringBuilder(ans));
  7. return;
  8. }
  9.  
  10. if(open>0){
  11. ans.append("(");
  12. solve(output,open - 1, close, ans);
  13. ans.delete(ans.length()-1,ans.length());
  14. }
  15.  
  16. if(close>open){
  17. ans.append(")");
  18. solve(output,open, close-1, ans);
  19. ans.delete(ans.length()-1,ans.length());
  20. }
  21. }
  22. public static void main(String[] args) {
  23.  
  24. int open = 2;
  25. int close = 2;
  26. StringBuilder ans= new StringBuilder();
  27. ArrayList<StringBuilder> output = new ArrayList<>();
  28.  
  29. solve(output,open,close,ans);
  30. for(StringBuilder s: output){
  31. System.out.println(s);
  32. }
  33.  
  34. }
  35. }
  36.  
  37. //here the output is correct
  38. //(())
  39. //()()
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement