创建排列以达到目标数字,但是重复使用提供的数字JavaScript
我们需要编写一个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 ] ]
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短