创建排列组合以达到目标数字,但重复使用提供的 JavaScript 数字
我们需要编写一个 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 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP