我们需要编写一个JavaScript函数,该函数将Integers数组arr作为第一个参数,并将单个整数target作为第二个参数。
对于数组中的每个Integer,我们的函数都可以为其分配“ +”或“-”。
我们的函数应该找出总共存在几种方式来分配“ +”,“-”,以使数组的整数总和等于目标总和target。
例如,如果函数的输入为-
const arr = [1, 1, 1, 1, 1]; const target = 3;
那么输出应该是-
const output = 5;
因为5种方式是-
-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
为此的代码将是-
const arr = [1, 1, 1, 1, 1];
const target = 3;
const waysToSum = (arr = [], target = 1) => {
const map = {};
const find = (arr, target, i) => {
let val = i + '->' + target;
if(map[val] !== undefined){
return map[val];
};
if(i === 0){
if (target === 0 && arr[0] === 0) { return 2 }
return arr[0] === target || arr[0] === -target ? 1 : 0
};
map[val] = find(arr, target + arr[i], i - 1) + find(arr, target - arr[i], i - 1);
return map[val]
};
return find(arr, target, arr.length-1)
};
console.log(waysToSum(arr, target));输出结果控制台中的输出将是-
5