public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
if(n<=0) {
return list;
}
dfs(list,0,2*n,"");
return list;
}
public void dfs(List<String> list, int pos,int n, String str) {
if(pos == n) {
if(islegal(str)) {
list.add(str);
}
return;
}
dfs(list,pos+1,n,str+"(");
dfs(list,pos+1,n,str+")");
}
public boolean islegal(String s){
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
int i = 1;
while(i < s.length()) {
if(stack.isEmpty()) {
stack.push(s.charAt(i++));
continue;
}
char c= stack.peek();
char o = s.charAt(i);
if(c == '(' && o == ')') {
stack.pop();
}else {
stack.push(o);
}
i++;
}
if(stack.isEmpty()) {
return true;
}else {
return false;
}
}
}
22. Generate Parentheses
最新推荐文章于 2024-07-09 23:43:07 发布