Given an integer array, return the total number of ways to calculate the specified target from array elements using only the addition and subtraction operator. The use of any other operator is forbidden.

For example,

Consider the array { 5, 3, -6, 2 }.
 
The total number of ways to reach a target of 6 using only + and – operators is 4 as:
 
(-)-6 = 6
(+) 5 (+) 3 (-) 2 = 6
(+) 5 (-) 3 (-) -6 (-) 2 = 6
(-) 5 (+) 3 (-) -6 (+) 2 = 6
 
Similarly, there are 4 ways to calculate the target of 4:
 
(-)-6 (-) 2 = 4
(-) 5 (+) 3 (-)-6 = 4
(+) 5 (-) 3 (+) 2 = 4
(+) 5 (+) 3 (+)-6 (+) 2 = 4

Practice this problem

We can use recursion to solve this problem. The idea is to recursively consider each array element, add or subtract its value from the target, and recur for the remaining elements with every element’s remaining target. Also recur with remaining elements with the same target by ignoring the element completely. Finally, return the number of times the desired target is reached at any point in the recursion.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

4 ways

Java


Download  Run Code

Output:

4 ways

Python


Download  Run Code

Output:

4 ways

The above solution is very similar to the famous 0–1 Knapsack Problem and runs in O(3^n) time, where n is the size of the input. The dynamic programming solution is recommended for large input, which is left as an exercise to the readers.

How can we extend the solution to print all pairs?

We can easily extend the solution to print all pairs of elements. The idea is to maintain a list to store the processed elements at any point, along with the information about the operator used.

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
(-)-6
(+)5 (+)3 (-)2
(+)5 (-)3 (-)-6 (-)2
(-)5 (+)3 (-)-6 (+)2