1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Solution {
public List<String> removeInvalidParentheses(String s) { if (s == null || s.length() == 0) return Arrays.asList("");
int numL = 0, numR = 0; for (char ch: s.toCharArray()){ if (ch == '(') numL++; else if (ch == ')'){ if (numL != 0) numL --; else numR++; } } HashSet<String> set = new HashSet<>(); helper(s, set, 0, "", numL, numR, 0); return new ArrayList<>(set); } private void helper(String s, HashSet<String> res, int idx, String cur, int numL, int numR, int open){ if (numL < 0 || numR < 0 || open < 0) return; if (idx == s.length()){ if (numL == 0 && numR == 0 && open == 0) res.add(new String(cur)); return; } if (s.charAt(idx) == '('){
helper(s, res, idx + 1, cur + "(", numL, numR, open + 1);
helper(s, res, idx + 1, cur, numL - 1, numR, open); } else if (s.charAt(idx) == ')'){
helper(s, res, idx + 1, cur + ")", numL, numR, open - 1);
helper(s, res, idx + 1, cur, numL, numR - 1, open); } else helper(s, res, idx + 1, cur + s.charAt(idx), numL, numR, open); } }
|