This page explains Java solution to problem `Expression Add Operators` using `Backtracking`.

## Problem Statement

Given a string that contains only digits `0-9` and a target value, return all possibilities to add binary operators (not unary) `+`, `-`, or `*` between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]

Example 2:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

## Solution

If you have any suggestions in below code, please create a pull request by clicking here.
``````
package com.vc.hard;

import java.util.*;

public List<String> addOperators(String num, int target) {
List<String> res = new ArrayList<>();
solve("", num, 0, 0, target, 0, res);
return res;
}

private void solve(String expr, String num, int index, long current, long target, long prev, List<String> res) {
if(current == target && index == num.length()) res.add(expr);
else {
for(int i = index; i < num.length(); i++) {
String digitStr = num.substring(index, i + 1);
if(digitStr.startsWith("0") && digitStr.length() > 1) break;
long digit = Long.parseLong(digitStr);
if(expr.equals("")) solve(digitStr, num, i + 1, digit, target, digit, res);
else {
solve(expr + "+" + digit, num, i + 1, current + digit, target, digit, res);
solve(expr + "-" + digit, num, i + 1, current - digit, target, -digit, res);
solve(expr + "*" + digit, num, i + 1, current - prev + prev * digit, target, prev * digit, res);
}
}
}
}
}
``````

## Time Complexity

O(N2 * 3N) Where
N is length of elements in an input string
At every step along the way, we consider exactly 3 different choices or 3 different recursive paths. The base case is when the value of index reaches N.

## Space Complexity

O(N) Where
N is length of elements in an input string