Skip to content

Commit 505ea2b

Browse files
one more backtracking solution
1 parent 4f275a5 commit 505ea2b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

MEDIUM/src/medium/GenerateParentheses.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,30 @@ public static void main(String...args){
3232
int n = 3;
3333
List<String> result = test.generateParenthesis(n);
3434
CommonUtils.print(result);
35+
36+
Solution2 sol2 = new Solution2();
37+
List<String> result2 = sol2.generateParenthesis(n);
38+
CommonUtils.print(result2);
39+
}
40+
41+
static class Solution2{
42+
public List<String> generateParenthesis(int n) {
43+
List<String> result = new ArrayList();
44+
if(n == 0) return result;
45+
helper(result, "", n, n);
46+
return result;
47+
}
48+
49+
void helper(List<String> result, String par, int left, int right){
50+
if(left > 0){
51+
helper(result, par+"(", left-1, right);
52+
}
53+
if(right > left){
54+
helper(result, par+")", left, right-1);
55+
}
56+
if(right == 0){
57+
result.add(par);
58+
}
59+
}
3560
}
3661
}

0 commit comments

Comments
 (0)