LeetCode -- Remove Invalid Parentheses
Description:
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 ()]
) (-> []
Input a string containing '(' and ')' and letters. Delete this string for the minimum number of times. If this string is deleted only once, the result is: str1 (The I bit is deleted), str2 (the j bit is deleted)..., strN.
Add the deleted strings to the result set that match the brackets (except for letters, '(' and ')' constitute a valid string.
Ideas:
1. You can use DFS or BFS for this question, but BFS is suitable because it is the minimum number of times rather than the first matching result.
2. if s does not meet the requirements, remove the I-th digit of s, and obtain the new strings t1, t2, t3... judge t [1... n] whether it meets the requirements. if it meets the requirements, add it to the result set in sequence; otherwise, t [0... n) join the queue.
3. The dictionary can be used for pruning because t has been judged during traversal.
Implementation Code:
public class Solution { public IList
RemoveInvalidParentheses(string s) { var ret = new List
(); var visited = new Dictionary
(); var q = new Queue
(); q.Enqueue(s); var next = new Queue
(); while(q.Count > 0){ var str = q.Dequeue(); if(IsValid(str)) { ret.Add(str); } else { for(var i = 0;i < str.Length; i++){ if(str[i] != '(' && str[i] != ')') continue; var t = str.Substring(0 , i) + str.Substring(i+1, str.Length - i - 1); if(!visited.ContainsKey(t)) { visited.Add(t , 1); next.Enqueue(t); } } } if(q.Count == 0){ if(ret.Count > 0){ break; } q = new Queue
(next); next.Clear(); } } if(ret.Count == 0){ ret.Add(); } return ret; }private bool IsValid(string s){var stack = new Stack
();for(var i = 0;i < s.Length; i++){if(s[i] == '('){stack.Push(s[i]);}else if(s[i] == ')'){if(stack.Count == 0){return false;}stack.Pop();}}return stack.Count == 0;}}