301. Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses (
and )
.
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
首先,遍历所有情况,然后看是否最后得到的string是否满足所有valid parentheses的情况,满足的话,就比较已经存在的valid parentheses. 否则就放弃。
1 public class Solution { 2 public List<String> removeInvalidParentheses(String s) { 3 List<String> list = new ArrayList<>(); 4 if (s == null) return list; 5 list.add(""); 6 helper(s, 0, "", 0, list); 7 return list; 8 } 9 10 void helper(String str, int index, String tempString, int leftCount, List<String> list) { 11 if (str.isEmpty() || leftCount > str.length() - index) return; 12 13 if (list.size() != 0 && list.get(0).length() > tempString.length() + str.length() - index) return; 14 15 if (index == str.length()) { 16 if (leftCount == 0) { 17 if (list.get(0).length() < tempString.length()) { 18 list.clear(); 19 list.add(tempString); 20 } else if (list.get(0).length() == tempString.length() && !list.contains(tempString)) { 21 list.add(tempString); 22 } 23 } 24 return; 25 } 26 27 if (str.charAt(index) == '(') { 28 helper(str, index + 1, tempString + "(", leftCount + 1, list); 29 helper(str, index + 1, tempString, leftCount, list); 30 } else if (str.charAt(index) == ')') { 31 if (leftCount != 0) { 32 helper(str, index + 1, tempString + ")", leftCount - 1, list); 33 } 34 helper(str, index + 1, tempString, leftCount, list); 35 } else { 36 helper(str, index + 1, tempString + str.charAt(index), leftCount, list); 37 } 38 } 39 }
1 public class Solution { 2 public List<String> removeInvalidParentheses(String s) { 3 List<String> res = new ArrayList<String>(); 4 int[] max = { 0 }; 5 dfs(s, "", 0, res, max); 6 if (res.size() == 0) { 7 res.add(""); 8 } 9 return res; 10 } 11 12 private void dfs(String str, String subRes, int countLeft, List<String> res, int[] max) { 13 if (countLeft > str.length()) return; 14 if (str.length() == 0) { 15 if (countLeft == 0 && subRes.length() != 0) { 16 if (subRes.length() > max[0]) { 17 max[0] = subRes.length();
res.clear(); 18 } 19 if (max[0] == subRes.length() && !res.contains(subRes)) { 20 res.add(subRes.toString()); 21 } 22 } 23 return; 24 } 25 26 if (str.charAt(0) == '(') { 27 dfs(str.substring(1), subRes + "(", countLeft + 1, res, max); 28 dfs(str.substring(1), subRes, countLeft, res, max); 29 } else if (str.charAt(0) == ')') { 30 if (countLeft > 0) { 31 dfs(str.substring(1), subRes + ")", countLeft - 1, res, max); 32 } 33 dfs(str.substring(1), subRes, countLeft, res, max); 34 } else { 35 dfs(str.substring(1), subRes + str.charAt(0), countLeft, res, max); 36 } 37 } 38 }