我们需要编写一个JavaScript函数,该函数将Numbers数组作为第一个参数,将目标总和Number作为第二个参数。
该函数应返回原始数组中所有这些子数组的数组,其元素总和构成目标总和。我们可以使用单个数字两次来获得总和。
例如-
如果输入数组和数字为-
const arr = [1, 2, 4]; const sum = 4;
那么输出应该是-
const output = [ [1, 1, 1, 1], [1, 1, 2], [2, 2], [4] ]
const arr = [1, 2, 4];
const sum = 4;
const getCombinations = (arr = [], sum) => {
const result = [];
const pushElement = (i, t) => {
const s = t.reduce(function (a, b) {
return a + b;
}, 0);
if (sum === s) {
result.push(t);
return;
};
if (s > sum || i === arr.length) {
return;
};
pushElement(i, t.concat([arr[i]]));
pushElement(i + 1, t);
}
pushElement(0, []);
return result;
};
console.log(getCombinations(arr, sum));输出结果
控制台中的输出将是-
[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]