ogv

Untitled

ogv
Sep 3rd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. public class Solution
  2. {
  3. public IList<string> RemoveInvalidParentheses(string s)
  4. {
  5. var results = new HashSet<string>();
  6. Enumerate("", s, 0, results);
  7. return results.ToList();
  8. }
  9.  
  10. private void Enumerate(string prefix, string s, int from, ISet<string> results)
  11. {
  12. if (from >= s.Length)
  13. {
  14. results.Add(prefix);
  15. return;
  16. }
  17.  
  18. int balance = 0;
  19. for (int i = from; i < s.Length; i++)
  20. {
  21. if (s[i] == '(') balance++;
  22. else if (s[i] == ')') balance--;
  23.  
  24. if (balance < 0)
  25. {
  26. for (int j = from; j <= i; j++)
  27. {
  28. if (s[j] == ')')
  29. {
  30. string newPrefix = s.Substring(from, i - from + 1);
  31. newPrefix = newPrefix.Remove(j - from, 1);
  32. Enumerate(prefix + newPrefix, s, i + 1, results);
  33. }
  34. }
  35. return;
  36. }
  37. }
  38.  
  39. if (balance == 0)
  40. {
  41. results.Add(prefix + s.Substring(from, s.Length - from));
  42. }
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment