Leetcode•Aug 12, 2025
Expression Add Operators
Hazrat Ali
Leetcode
Given a string num
that contains only digits and an integer target
, return all possibilities to insert the binary operators '+'
, '-'
, and/or '*'
between the digits of num
so that the resultant expression evaluates to the target
value.
Note that operands in the returned expressions should not contain leading zeros.
Note that a number can contain multiple digits.
Example 1:
Input: num = "123", target = 6 Output: ["1*2*3","1+2+3"] Explanation: Both "1*2*3" and "1+2+3" evaluate to 6.
Example 2:
Input: num = "232", target = 8 Output: ["2*3+2","2+3*2"] Explanation: Both "2*3+2" and "2+3*2" evaluate to 8.
Example 3:
Input: num = "3456237490", target = 9191 Output: [] Explanation: There are no expressions that can be created from "3456237490" to evaluate to 9191.
Solution
/**
* @param {string} num
* @param {number} target
* @return {string[]}
*/
const addOperators = (num, target) => {
const result = [];
backtracking(num, target, 0, 0, 0, '', result);
return result;
};
const backtracking = (num, target, start, total, last, solution, result) => {
if (start === num.length) {
if (total === target) {
result.push(solution);
}
return;
}
for (let i = start; i < num.length; i++) {
if (i > start && num[start] === '0') {
break;
}
const curr = parseInt(num.substring(start, i + 1));
if (start === 0) {
backtracking(num, target, i + 1, total + curr, curr, solution + curr, result);
} else {
backtracking(num, target, i + 1, total + curr, curr, solution + '+' + curr, result);
backtracking(num, target, i + 1, total - curr, -curr, solution + '-' + curr, result);
backtracking(num, target, i + 1, total - last + last * curr, last * curr, solution + '*' + curr, result);
}
}
};