Skip to content

Commit df960d3

Browse files
committed
generate parentheses
1 parent 8ca25ca commit df960d3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/generate-parentheses/
8+
public class GenerateParentheses {
9+
10+
public static void main(String[] args) {
11+
GenerateParentheses obj = new GenerateParentheses();
12+
List<String> result = obj.generateParenthesis(3);
13+
System.out.println("result > " + Arrays.toString(result.toArray()));
14+
}
15+
16+
public List<String> generateParenthesis(int n) {
17+
List<String> result = new ArrayList<>();
18+
if (n <= 0) {
19+
return result;
20+
}
21+
22+
helper(result, "", n, n);
23+
24+
return result;
25+
}
26+
27+
public void helper(List<String> result, String combine, int left, int right) {
28+
//exit
29+
if (left == 0 && right == 0) {
30+
result.add(combine);
31+
return;
32+
}
33+
34+
if (left > 0) {
35+
helper(result, combine + '(', left - 1, right);
36+
}
37+
if (right > left) {
38+
helper(result, combine + ')', left, right - 1);
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)