-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution22.java
More file actions
39 lines (35 loc) · 1.17 KB
/
Solution22.java
File metadata and controls
39 lines (35 loc) · 1.17 KB
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
37
38
39
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Created by Alex on 2016/2/22.
*/
public class Solution22 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
generateParenthesis("", n, 0, 0, result);
return result;
}
public void generateParenthesis(String temp, int n, int left, int right, List<String> result){
if(left < n){
generateParenthesis(temp+"(", n, left+1, right, result);
}
if(right < n){
generateParenthesis(temp+")", n, left, right+1, result);
}
if(left == n && right == n){
Stack<String> stack = new Stack<String>();
for(int i = 0; i < temp.length(); i++){
String character = temp.substring(i, i+1);
if(character.equals(")") && !stack.isEmpty() && stack.peek().equals("(")){
stack.pop();
}else {
stack.push(character);
}
}
if(stack.isEmpty()){
result.add(temp);
}
}
}
}