1. Generate All Operator Strings + Calculator Evaluator
Intuition
Between N digits, there are N-1 slots, each taking 1 of 4 choices (empty, +, -, *), generating 4^(N-1) expression strings. Each string is verified for leading zeros and passed to a full stack-based arithmetic evaluator.
When to apply: Baseline comparison to illustrate the benefit of maintaining running evaluations.
Algorithm
- Generate all 4^(N-1) possible expression strings.
- Check each expression string to ensure no multi-digit number starts with
0. - Evaluate the expression using standard BODMAS/PEMDAS evaluator.
- If evaluated value == target, add expression to result.
#include <iostream>#include <vector>#include <string>#include <stack>#include <cctype> using namespace std; class Solution { long long evaluate(const string& s) { stack<long long> st; char sign = '+'; long long num = 0; int n = s.length(); for (int i = 0; i < n; i++) { char c = s[i]; if (isdigit(c)) num = num * 10 + (c - '0'); if (i == n - 1 || (!isdigit(c))) { if (sign == '+') st.push(num); else if (sign == '-') st.push(-num); else if (sign == '*') { long long top = st.top(); st.pop(); st.push(top * num); } sign = c; num = 0; } } long long total = 0; while (!st.empty()) { total += st.top(); st.pop(); } return total; } bool isValid(const string& s) { int n = s.length(); for (int i = 0; i < n; i++) { if (s[i] == '0') { if (i == 0 || !isdigit(s[i - 1])) { if (i + 1 < n && isdigit(s[i + 1])) return false; // leading zero } } } return true; } public: void generate(int idx, const string& num, string current, vector<string>& result, long long target) { if (idx == num.length()) { if (isValid(current) && evaluate(current) == target) { result.push_back(current); } return; } char nextChar = num[idx]; // 4 choices generate(idx + 1, num, current + nextChar, result, target); generate(idx + 1, num, current + "+" + nextChar, result, target); generate(idx + 1, num, current + "-" + nextChar, result, target); generate(idx + 1, num, current + "*" + nextChar, result, target); } vector<string> addOperators(string num, int target) { vector<string> result; if (num.empty()) return result; string initial = ""; initial += num[0]; generate(1, num, initial, result, target); return result; }}; int main() { Solution sol; auto res = sol.addOperators("123", 6); for (const string& s : res) cout << s << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(4^N * N)— Generates 4^(N-1) strings, and evaluates each string in O(N) time with a stack. - Space complexity:
O(N)— String buffers and expression parser stack take O(N) memory.