[LeetCode] 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 in letters other than the parentheses(And).
Examples:
"()"-> ["()", "()"]
"(A) ()"-> ["(a) ()", "(a ()"]
") ("-> [""]
Solutions
Parentheses always appear in pairs, so we only need to record the unmatched(.
There are three situations in each loop:
(.
)If we have unmatched
(. Retain other characters.
Because we need to remove the minimum number of parentheses, we should get the maximum match.()Number. Pay attention to the order of the following two rows.
dfs(str.substring(1), subRes + '(', countLeft + 1, maxLeft + 1);dfs(str.substring(1), subRes, countLeft, maxLeft);
It ensures that the longest result appears before the shorter result.
Implementation Code
Java:
// Runtime: 216 mspublic class Solution { private List
res = new ArrayList
(); private int max = 0; public List
removeInvalidParentheses(String s) { dfs(s, , 0, 0); if (res.size() == 0) { res.add(); } return res; } private void dfs(String str, String subRes, int countLeft, int maxLeft) { if (str.length() == 0) { if (countLeft == 0 && subRes.length() != 0) { if (maxLeft > max) { max = maxLeft; } if (max == maxLeft && !res.contains(subRes)) { res.add(subRes.toString()); } } return; } if (str.charAt(0) == '(') { dfs(str.substring(1), subRes.concat((), countLeft + 1, maxLeft + 1); dfs(str.substring(1), subRes, countLeft, maxLeft); } else if (str.charAt(0) == ')') { if (countLeft > 0) { dfs(str.substring(1), subRes.concat()), countLeft - 1, maxLeft); } dfs(str.substring(1), subRes, countLeft, maxLeft); } else { dfs(str.substring(1), subRes.concat(String.valueOf(str.charAt(0))), countLeft, maxLeft); } }}