1. Generate All 2^(2N) Sequences + Validator
Intuition
Recursively build all 2^(2N) binary strings of length 2N. For each complete string, check if it is valid: balance must never drop below 0 and must finish at 0.
When to apply: Baseline comparison to illustrate the exponential difference between generating everything vs guided pruning.
Algorithm
- Recursively generate all 2^(2N) strings.
- Check validity: iterate chars, increment for
(, decrement for). If balance < 0, invalid. If final balance == 0, valid. - Collect all valid strings into
result.
#include <iostream>#include <vector>#include <string> using namespace std; class Solution { bool isValid(const string& s) { int bal = 0; for (char c : s) { if (c == '(') bal++; else bal--; if (bal < 0) return false; } return bal == 0; } void generateAll(string current, int n, vector<string>& result) { if (current.length() == 2 * n) { if (isValid(current)) result.push_back(current); return; } generateAll(current + '(', n, result); generateAll(current + ')', n, result); } public: vector<string> generateParenthesis(int n) { vector<string> result; generateAll("", n, result); return result; }}; int main() { Solution sol; auto res = sol.generateParenthesis(3); for (const string& s : res) cout << s << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^(2N) * N)— Generates 2^(2N) strings, each verified in O(N) time. - Space complexity:
O(N)— Recursion depth is 2N.