Problem 301: Remove Invalid Parentheses
思路
复杂度
public class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> rst = new ArrayList<String>();
helper(s, rst, 0, 0, new char[] {'(', ')'});
return rst;
}
private void helper(String s, List<String> rst, int last_j, int last_i, char[] ch) {
int count = 0;
for (int i = last_i; i < s.length(); i++) {
if (s.charAt(i) == ch[0]) count++;
if (s.charAt(i) == ch[1]) count--;
if (count >= 0) continue;
for (int j = last_j; j <= i; j++) {
if (s.charAt(j) == ch[1] && (j == last_j || s.charAt(j - 1) != ch[1])) {
helper(s.substring(0, j) + s.substring(j + 1, s.length()), rst, j, i, ch);
}
}
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (ch[0] == '(') { // finished left to right
helper(reversed, rst, 0, 0, new char[] {')', '('});
} else { // finished right to left
rst.add(reversed);
}
}
}易错点
Last updated
