Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. //Even though this was in a Mock. Gos the result in Geeks. Questão dificil do kct. :)
  2. class Solution {
  3. // Utility recursive method to generate all possible
  4. // expressions
  5. void getExprUtil(vector<string>& res, string curExp,
  6.                  string input, int target, int pos,
  7.                  int curVal, int last)
  8. {
  9.     // true if whole input is processed with some
  10.     // operators
  11.     if (pos == input.length())
  12.     {
  13.         // if current value is equal to target
  14.         //then only add to final solution
  15.         // if question is : all possible o/p then just
  16.         //push_back without condition
  17.         if (curVal == target)
  18.             res.push_back(curExp);
  19.         return;
  20.     }
  21.  
  22.     // loop to put operator at all positions
  23.     for (int i = pos; i < input.length(); i++)
  24.     {
  25.         // ignoring case which start with 0 as they
  26.         // are useless for evaluation
  27.         if (i != pos && input[pos] == '0')
  28.             break;
  29.  
  30.         // take part of input from pos to i
  31.         string part = input.substr(pos, i + 1 - pos);
  32.  
  33.         // take numeric value of part
  34.         int cur = atoi(part.c_str());
  35.  
  36.         // if pos is 0 then just send numeric value
  37.         // for next recurion
  38.         if (pos == 0)
  39.             getExprUtil(res, curExp + part, input,
  40.                      target, i + 1, cur, cur);
  41.  
  42.  
  43.         // try all given binary operator for evaluation
  44.         else
  45.         {
  46.             getExprUtil(res, curExp + "+" + part, input,
  47.                      target, i + 1, curVal + cur, cur);
  48.             getExprUtil(res, curExp + "-" + part, input,
  49.                      target, i + 1, curVal - cur, -cur);
  50.             getExprUtil(res, curExp + "*" + part, input,
  51.                      target, i + 1, curVal - last + last * cur,
  52.                      last * cur);
  53.         }
  54.     }
  55. }
  56.  
  57. public:
  58.     // Below method returns all possible expression
  59.     // evaluating to target
  60.     vector<string> addOperators(string num, int target) {
  61.         vector<string> res;
  62.         getExprUtil(res, "", num, target, 0, 0, 0);
  63.         return res;
  64.     }
  65. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement