【LeetCode】【HOT】301. 删除无效的括号
package hot;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution301 {
public static void main(String[] args) {
String s = "(a)())()";
Solution301 solution = new Solution301();
System.out.println(solution.method(s));
}
int n;
int max;
int len;
String s;
Set<String> set = new HashSet<>();
private List<String> method(String s){
this.s = s;
n = s.length();
int l = 0;
int r = 0;
for(char c : s.toCharArray()){
if(c == '(') l++;
else if(c == ')') r++;
}
max = Math.min(l, r);
dfs(0, "", 0);
return new ArrayList<>(set);
}
private void dfs(int u, String cur, int score){
if(score > max || score < 0) return;
if(u == n){
if(score == 0 && cur.length() >= len){
if(cur.length() > len) set.clear();
len = cur.length();
set.add(cur);
}
return;
}
char c = s.charAt(u);
if(c == '('){
dfs(u+1, cur + c, score + 1);
dfs(u+1, cur, score);
}else if(c == ')'){
dfs(u+1, cur + c, score -1);
dfs(u+1, cur, score);
}else{
dfs(u+1,cur + c, score);
}
}
}