您的位置:首页 > 其它

Remove Invalid Parentheses

2016-07-08 22:11 405 查看
public class Solution {
int max = 0;
public List<String> removeInvalidParentheses(String s) {
if (s == null) {
throw new IllegalArgumentException("haha");
}
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 leftMax) {
if (left.length() == 0) {
if (leftCount == 0 && right.length() > 0) {
if (leftMax > max) {
max = leftMax;
}
if (leftMax == max && !res.contains(right)) {
res.add(right);
}
}
return;
}
if (left.charAt(0) == '(') {
helper(res, left.substring(1), right + '(', leftCount + 1, leftMax + 1);
helper(res, left.substring(1), right, leftCount, leftMax);
} else if (left.charAt(0) == ')') {
if (leftCount > 0) {
helper(res, left.substring(1), right + ')', leftCount - 1, leftMax);
}
helper(res, left.substring(1), right, leftCount, leftMax);
} else {
helper(res, left.substring(1), right + left.charAt(0), leftCount, leftMax);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: