# Print all possible expressions that evaluate to a target in C++

In this problem, we are given a string of integers from 0 to 9 and a target value. We have to print out ways in which we can generate expression using +, -, and * operation which is evaluated to the value equal to target.

Let’s take an example to understand the topic better −

Input: string = “123” , target= 6
Output: { “1+2+3”, “1*2*3” }

To solve this problem, we will be creating expressions by placing all possible binary operators between digits and then checking the result of the expression with the target value.

We will pass all values to a recursive method that will evaluate the resultant expression. If the number starts at 0, then we will ignore it.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void generateExpressionForTarget(vector<string>& res, string curExp,
string input, int target, int pos,int curVal, int last){
if (pos == input.length()){
if (curVal == target)
res.push_back(curExp);
return;
}
for (int i = pos; i < input.length(); i++){
if (i != pos && input[pos] == '0')
break;
string part = input.substr(pos, i + 1 - pos);
int cur = atoi(part.c_str());
if (pos == 0)
generateExpressionForTarget(res, curExp + part, input, target, i + 1, cur, cur);
else{
generateExpressionForTarget(res, curExp + "+" + part, input, target, i + 1, curVal + cur, cur);
generateExpressionForTarget(res, curExp + "-" + part, input, target, i + 1, curVal - cur, -cur);
generateExpressionForTarget(res, curExp + "*" + part, input, target, i + 1, curVal - last + last * cur, last * cur);
}
}
}
vector<string>generateExpression(string input, int target){
vector<string> res;
generateExpressionForTarget(res, "", input, target, 0, 0, 0);
return res;
}
int main(){
string input = "345";
int target = 12;
cout<<"The expressions are: \n";
vector<string> res = generateExpression(input, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
cout << endl;
return 0;
}

## Output

The expressions are −

3+4+5

Updated on: 17-Jan-2020

183 Views