Target Number

Problem

There are n non-negative integers. We want to add or subtract these numbers appropriately to make our target number. For example, to make the number 3 from [1, 1, 1, 1, 1], you can use the following five methods:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

Write the solution function to return the number of ways to make the target number by adding and subtracting the numbers appropriately when the array numbers, target number, and target are given as parameters.

Restrictions

  • The number of numbers given is 2 or more and 20 or less.
  • Each number is a natural number from 1 to 50.
  • A target number is a natural number from 1 to 1000.

I/O example

numbers target return
[1, 1, 1, 1, 1] 3 5

I/O example explanation

Same as the example in the problem.

My Solution

function solution(numbers, target) {
	let answer = 0;

	function recur(idx, sum) {
		if (idx === numbers.length) {
			if (sum === target) {
				answer++;
			}
			return;
		}

		recur(idx + 1, sum + numbers[idx]);
		recur(idx + 1, sum - numbers[idx]);
	}
	recur(0, 0);

	return answer;
}