Skip to content

Commit 481166e

Browse files
authored
Add files via upload
1 parent 2341fb8 commit 481166e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Backtracking/GenerateParentheses.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//LeetCode 22. Generate Parentheses
2+
//Question - https://leetcode.com/problems/generate-parentheses/
3+
4+
class Solution {
5+
public List<String> generateParenthesis(int n) {
6+
List<String> res = new ArrayList<>();
7+
helper("", res, 0, 0, n);
8+
return res;
9+
}
10+
11+
public void helper(String str, List<String> l, int open, int close, int n){
12+
if(str.length() == n*2){
13+
l.add(str);
14+
return;
15+
}
16+
17+
//each valid parentheses must have n open braces and not more.
18+
if(open < n) helper(str + '(', l, open + 1, close, n);
19+
//To maintain a valid parentheses, the closed brackets can only be added when
20+
//we have corresponding open brackets available.
21+
if(close < open) helper(str + ')', l, open, close + 1, n);
22+
}
23+
}

0 commit comments

Comments
 (0)