Viết hàm JS nhận một mảng số và một tổng mục tiêu. Hàm trả về mảng các mảng con (có thể lặp lại phần tử) mà tổng bằng mục tiêu.
Ví dụ: arr = [2,3,6,7], sum = 7 → [[2,2,3], [7]].
Ví dụ
const arr = [2, 3, 6, 7], sum = 7;
const combineElements = (arr, sum) => {
const output = [];
const findCombination = (remain, path, start) => {
if (remain < 0) return;
if (remain === 0) {
output.push([...path]);
return;
}
for (let i = start; i < arr.length; i++) {
findCombination(remain - arr[i], [...path, arr[i]], i);
}
};
findCombination(sum, [], 0);
return output;
};
console.log(combineElements(arr, sum)); // [[2,2,3], [7]]
Kết quả
[ [ 2, 2, 3 ], [ 7 ] ]