Expression Add Operators in C++


Suppose we have a string that holds only digits from 0 to 9. And one target value is given. We have to return all possibilities to add binary operators +, - and * into the digits to get the target values. So if the input is like “232” and the target is 8, then the answer will be [“2*3+2”, “2+3*2”]

To solve this, we will follow these steps −

  • Define a method called solve(), this will take index, s, curr, target, temp, mult −

  • if idx >= size of s, then,

    • if target is same as curr, then,

      • insert temp at the end of ret

    • return

  • aux := empty string

  • for initializing i := idx, when i < size of s, increase i by 1 do −

    • aux = aux + s[i]

    • if aux[0] is same as '0' and size of aux> 1, then,

      • Skip to the next iteration, ignore following part

    • if idx is same as 0, then,

      • call solve(i + 1, s, aux as integer, target, aux, aux as integer)

    • Otherwise

      • call solve(i + 1, s, curr + aux as integer, target, temp + " + " + aux, aux as integer)

      • call solve(i + 1, s, curr - aux as integer, target, temp + " - " + aux, - aux as integer)

      • call solve(i + 1, s, curr - mult + mult * aux as integer, target, temp + " * " + aux, mult * aux as integer)

  • From the main method call solve(0, num, 0, target, empty string, 0)

  • return ret

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
   public:
   vector <string> ret;
   void solve(int idx, string s, lli curr, lli target, string temp, lli mult){
      //cout << temp << " " << curr << endl;
      if(idx >= s.size()){
         if(target == curr){
            ret.push_back(temp);
         }
         return;
      }
      string aux = "";
      for(int i = idx; i < s.size(); i++){
         aux += s[i];
         if(aux[0] == '0' && aux.size() > 1) continue;
         if(idx == 0){
            solve(i + 1, s, stol(aux), target, aux, stol(aux));
         } else {
            solve(i + 1, s, curr + stol(aux), target, temp + "+" + aux, stol(aux));
            solve(i + 1, s, curr - stol(aux), target, temp + "-" + aux, -stol(aux));
            solve(i + 1, s, curr - mult + mult * stol(aux), target, temp + "*" + aux, mult * stol(aux));
         }
      }
   }
   vector<string> addOperators(string num, int target) {
      solve(0, num, 0, target, "", 0);
      return ret;
   }
};
main(){
   Solution ob;
   print_vector(ob.addOperators("232", 8));
}

Input

"232", 8

Output

[2+3*2, 2*3+2, ]

Updated on: 27-May-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements