Advertisement
Akshansh0Sharma

String parenthesis

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