Practice › Recursion & Backtracking
Expression Add Operators
Hard · Recursion & Backtracking · Asked at Google, Meta, Amazon, Uber
Between the digits of the string you may insert +, - or * (or nothing, joining digits into a longer number). A number with more than one digit may not start with 0. Print how many different expressions evaluate to target (with the usual rule that * is done before + and -).
Input
First line: the digit string. Second line: target.
Output
The number of expressions that equal target.
Constraints
- 1 ≤ length ≤ 10
- −2^31 ≤ target ≤ 2^31 − 1
Backtrack over where the next number ends and which operator comes before it. Track the value so far and the last multiplied term: for
*, value = value − last + last × num and last = last × num. Use 64-bit integers.
Example 1
Input
123 6
Output
2
Example 2
Input
232 8
Output
2
Example 3
Input
3456237490 9191
Output
0
Hints
- At each step choose where the next number ends, then which operator joins it.
- Multiplication binds tighter: remember the last term so you can undo its addition.
- Numbers like "05" are not allowed — stop extending a number that starts with 0.
Approach
go(i, value, last): i is where the next number starts. For every end j, num = s[i..j) (break if it has a leading zero). At i = 0 the number simply starts the expression. Otherwise branch: "+" gives (value + num, num); "−" gives (value − num, −num); "*" gives (value − last + last × num, last × num) — the previous term is replaced by its product. Count the expressions whose value equals the target at the end. Values reach about 10^18 for ten 9s, which still fits in 64 bits.
Complexity: O(4^n) time · O(n) recursion depth
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
string s;
long long target, countWays = 0;
void go(size_t i, long long value, long long last) {
if (i == s.size()) {
if (value == target) countWays++;
return;
}
for (size_t j = i + 1; j <= s.size(); j++) {
if (j > i + 1 && s[i] == '0') break;
long long num = stoll(s.substr(i, j - i));
if (i == 0) go(j, num, num);
else {
go(j, value + num, num);
go(j, value - num, -num);
go(j, value - last + last * num, last * num);
}
}
}
int main() {
cin >> s >> target;
go(0, 0, 0);
cout << countWays << "\n";
return 0;
}Python solution
import sys
s, target = sys.stdin.read().split()[:2]
target = int(target)
n = len(s)
count = 0
def go(i, value, last):
global count
if i == n:
if value == target:
count += 1
return
for j in range(i + 1, n + 1):
if j > i + 1 and s[i] == "0":
break
num = int(s[i:j])
if i == 0:
go(j, num, num)
else:
go(j, value + num, num)
go(j, value - num, -num)
go(j, value - last + last * num, last * num)
go(0, 0, 0)
print(count)Java solution
import java.util.*;
public class Main {
static String s;
static long target, count = 0;
static void go(int i, long value, long last) {
if (i == s.length()) {
if (value == target) count++;
return;
}
for (int j = i + 1; j <= s.length(); j++) {
if (j > i + 1 && s.charAt(i) == '0') break;
long num = Long.parseLong(s.substring(i, j));
if (i == 0) go(j, num, num);
else {
go(j, value + num, num);
go(j, value - num, -num);
go(j, value - last + last * num, last * num);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
s = sc.next();
target = sc.nextLong();
go(0, 0, 0);
System.out.println(count);
}
}Solve Expression Add Operators online · All practice problems