-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidParentheses.java
43 lines (24 loc) · 1.04 KB
/
ValidParentheses.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
class ValidParentheses{
public static void main(String[] args)
{
ArrayList<String> parenthesSeries = generateParenthesis(5);
for (String p : parenthesSeries) {
System.out.println(p);
}
}
private static ArrayList<String> generateParenthesis(int howManyPairs) {
ArrayList<String> result = new ArrayList<>();
String initialString = "";
recurOverParentheses(result, initialString, howManyPairs, howManyPairs);
return result;
}
private static void recurOverParentheses(ArrayList<String> result, String currentString, int opening, int closing)
{
if (opening == 0 && closing == 0) result.add(currentString);
if (opening > closing || opening < 0 || closing < 0) return;
String stringPlusLeft = currentString + "(";
recurOverParentheses( result, stringPlusLeft,opening - 1, closing);
String stringPlusRight = currentString + ")";
recurOverParentheses(result, stringPlusRight, opening, closing - 1);
}
}