1. Breadth-First Search (BFS) Level by Level
Intuition
Maintain a visited set and a queue. For each popped string, if valid, collect it and set found = true. Otherwise, if not found yet, generate all candidate substrings by deleting one parenthesis and enqueue them.
Algorithm
- Step 1: Generate all 2N possible sub-sequences by removing subsets of characters.
- Step 2: Filter the generated strings to retain only valid parentheses expressions.
- Step 3: Keep strings of maximum length (minimum removals) and remove duplicates using a Set.
- Step 4: Return result list.
#include <iostream>#include <vector>#include <string>#include <queue>#include <unordered_set> class Solution {public: bool isValid(const std::string& s) { int count = 0; for (char c : s) { if (c == '(') count++; else if (c == ')') { count--; if (count < 0) return false; } } return count == 0; } std::vector<std::string> removeInvalidParentheses(std::string s) { std::vector<std::string> result; std::unordered_set<std::string> visited; std::queue<std::string> q; q.push(s); visited.insert(s); bool found = false; while (!q.empty()) { int sz = q.size(); for (int k = 0; k < sz; k++) { std::string curr = q.front(); q.pop(); if (isValid(curr)) { result.push_back(curr); found = true; } if (found) continue; for (int i = 0; i < (int)curr.length(); i++) { if (curr[i] != '(' && curr[i] != ')') continue; std::string next = curr.substr(0, i) + curr.substr(i + 1); if (!visited.count(next)) { visited.insert(next); q.push(next); } } } if (found) break; } return result; }}; int main() { Solution solver; std::vector<std::string> res = solver.removeInvalidParentheses("()())()"); std::cout << "BFS Output for '()())()':\n"; for (const auto& str : res) { std::cout << "\"" << str << "\"\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(2^N * N)— Explores levels until minimum removal depth is reached. - Space complexity:
O(2^N * N)— The BFS queue and visited set store up to O(2N) substrings.