public class Solution {
int max = 0;
public List<String> removeInvalidParentheses(String s) {
List<String> res = new LinkedList<>();
helper(res, s, "", 0, 0);
if (res.size() == 0) {
res.add("");
}
return res;
}
private void helper(List<String> res, String left, String right, int leftCount, int maxCount) {
if (left.length() == 0) {
if (leftCount == 0 && right.length() != 0) {
if (maxCount > max) {
max = maxCount;
}
if (maxCount == max && !res.contains(right)) {
res.add(right);
}
}
return;
}
if (left.charAt(0) == '(') {
helper(res, left.substring(1), right + '(', leftCount + 1, maxCount + 1);
helper(res, left.substring(1), right, leftCount, maxCount);
} else if (left.charAt(0) == ')') {
if (leftCount > 0) {
helper(res, left.substring(1), right + ')', leftCount - 1, maxCount);
}
helper(res, left.substring(1), right, leftCount, maxCount);
} else {
helper(res, left.substring(1), right + left.charAt(0), leftCount, maxCount);
}
}
}
Remove Invalid Parentheses
最新推荐文章于 2020-06-27 21:00:25 发布