-
Notifications
You must be signed in to change notification settings - Fork 0
/
ques18.java
36 lines (29 loc) · 986 Bytes
/
ques18.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;
//Generate Parentheses
//Leetcode Link -> https://leetcode.com/problems/generate-parentheses/description/
public class ques18 {
public static void gen(int n, int open, int close, String ans, ArrayList<String> arr) {
if (open == n && close == open) {
arr.add(ans);
return;
}
if (open > n || close > open) {
return;
}
gen(n, open + 1, close, ans + "(", arr);
gen(n, open, close + 1, ans + ")", arr);
}
public static List<String> generateParenthesis(int n) {
ArrayList<String> arr = new ArrayList<>();
gen(n, 0, 0, "", arr);
return arr;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<String> arr = generateParenthesis(n);
for (String s : arr) {
System.out.println(s);
}
}
}