创建排列以达到目标数字,但重用提供的数字 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数将数字数组作为第一个参数,将目标和数字作为第二个参数。
该函数应返回原始数组中所有子数组的数组,这些子数组的元素总和达到目标和。我们可以使用一个数字两次来实现总和。
例如 −
如果输入数组和数字是 −
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 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

