What would be the best way (in C) to get all sums of N numbers in an array, by using addition and subtraction?
For example (N = 3):
arr[] = [30, 14, 2]
results:
-30-14-2 = -46
-30-14+2 = -42
-30+14-2 = -18
-30+14+2 = -14
30-14-2 = 14
30-14+2 = 18
30+14-2 = 42
30+14+2 = 46
As can be seen, there are 2^N solutions.
I also noticed that the addition an subtraction symbols alternate in the same way as binary counting (000 001 … 110 111), which might be useful.
Probably a recursive approach would be best, but I find it very hard to think recursively.
Therefore, I hope someone can explain to me what the best strategy would be to tackle this problem.
——————————
EDIT:
I have a working Python code, but this uses sets set(), which aren’t available in C. (arr is an array containing all numbers.)
out = set()
out.add(0)
for i in range(0, len(arr)):
tmp = set()
for j in out:
tmp.add(j + arr[i])
tmp.add(j - arr[i])
out = tmp
print(out)
——————————
EDIT:
With replacing the sets by arrays and making a few small changes, I got it working. Thanks to everyone who commented!