public class Solution { public IListRemoveInvalidParentheses(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; } }