leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0241.cpp (818B)


      1 class Solution {
      2     int operate(char op, int a, int b) {
      3         switch (op) {
      4         case '+': return a + b;
      5         case '-': return a - b;
      6         case '*': return a * b;
      7         }
      8         return 0;
      9     }
     10 
     11     vector<int> rec(const string &expression, int start, int end) {
     12         vector<int> res;
     13         for (int i = start; i < end; i++) {
     14             if (isdigit(expression[i])) continue;
     15             for (auto n1 : rec(expression, start, i))
     16                 for (auto n2 : rec(expression, i + 1, end))
     17                     res.push_back(operate(expression[i], n1, n2));
     18         }
     19         if (res.empty()) return {stoi(expression.substr(start, end - start))};
     20         return res;
     21     }
     22 
     23   public:
     24     vector<int> diffWaysToCompute(const string &expression) { return rec(expression, 0, expression.size()); }
     25 };